java – Finding sequential numbers that multiplied is a result

Question:

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

Answer:

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

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:

It 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 search down to 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.

Scroll to Top
AllEscort