Discover numbers in sequence that multiplied is a result

3

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

    
asked by anonymous 12.03.2017 / 23:47

2 answers

0
Mathematically, this situation can only occur for positive numbers that are not perfect squares, and to find out whether the number in question falls into this situation, one has to test whether the square root rounded down multiplied by the square root rounded upward results in number concerned. Validating the other numbers 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 [];
}
    
13.03.2017 / 02:52
1

Just a for 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 sample outputs:

  

Found 128 and 129 as factors followed by 16512

     

No multiplier found for 16513

     

Found 99 and 100 as factors followed by 9900

     

Found 2 and 3 as factors followed by 6

     

No multiplier found for 78

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

    
12.03.2017 / 23:54