Finding numbers in sequence that multiplied is a result

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

Author: Guilherme ZM, 2017-03-12

2 answers

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 this situation, simply test whether the square root rounded down multiplied by the square root rounded up result in the number in question. Validate the other numbers, it would be just waste.

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 [];
}
 0
Author: falsarella, 2017-11-21 19:01:16

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

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 outputs:

Found 128 and 129 as factors followed by 16512

No multiplier number found for 16513

Found 99 and 100 as factors followed by 9900

Found 2 and 3 as factors followed by 6

No multiplier number found for 78

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

 1
Author: Rafael B., 2020-06-11 14:45:34