Finding numbers in sequence that multiplied is a result

Asked

Viewed 1,046 times

3

I helped my cousin solve a math exercise today. The exercise called for two numbers in sequence that when multiplied the result is 16512 (128 * 129). I would like to know a code that would solve this with any number.

2 answers

1

Just one for up to the square root of the number sought:

public class Multiplicador {

    public static void main(String args[]) {
        try {
            int i = 16512;
            int j = encontraPrimeiroNumeroMultiplicador(i);
            System.out.println("Encontrou " + j + " e " + (j+1) + " como fatores seguidos de " + i);
            
        } catch (Exception e) {
             System.err.println(e);    
        }
    }
    
    public static int encontraPrimeiroNumeroMultiplicador(int numeroProcurado) throws Exception {
        for(int i=0; i<=Math.sqrt(numeroProcurado+1); i++) {
            
            if(i * (i+1) == numeroProcurado) {
                return i;
            }
        }
        throw new Exception("Nenhum numero multiplicador encontrado para " + numeroProcurado);
    }
}

Some examples of exits:

Found 128 and 129 as factors followed from 16512

No multiplier number found for 16513

Found 99 and 100 as following factors of 9900

Found 2 and 3 as factors followed by 6

No multiplier number found for 78

Why is it enough to search to the square root? Because no number multiplied by its successor will be less than the number squared; that is, N * (N+1) will be greater than N * N, for any positive natural number.

0


Mathematically, this situation can only occur for positive numbers that are not perfect squares, and to find out if the number in question falls into that situation, it is sufficient to test whether the square root rounded downwards multiplied by the square root rounded upwards result in the number in question. Validate the other numbers, it would just be wasted.

Following this line of reasoning, consider the following code:

// dado "numero", retorna:
// 1) [a, b], onde "a * b == numero", e "a" e "b" são consecutivos
// 2) [], quando não existem números consecutivos que multiplicados resultam em "numero"
public static int[] obtemConsecutivos(int numero) {
    // previne erro na raizQuadrada com números negativos
    if (numero > 0) {
        long raiz = Math.sqrt(numero);
        int primeiroConsecutivo = Math.floor(raiz);
        int segundoConsecutivo = Math.ceil(raiz);
        // previne situação de quadrado perfeito, como 4, 9, 16, 25...
        // nesse caso, o primeiro consecutivo será igual ao segundo
        if (primeiroConsecutivo + 1 == segundoConsecutivo) {
            // testa se consecutivos batem com o numero desejado
            if (numero == primeiroConsecutivo * segundoConsecutivo) {
                return [primeiroConsecutivo, segundoConsecutivo];
            }
        }
    }
    return [];
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.