How to print only numbers that are repeated between two different formulas?

0

I have two 50-number formulas. One has multiples of 3 and the other multiples of 7 .

Code:

public static void main(String[] args) {           
    BigInteger start = new BigInteger("1");
    BigInteger limit = new BigInteger("50");
    BigInteger n1 = new BigInteger("3");
    BigInteger n2 = new BigInteger("7");

    for (BigInteger a = start; a.compareTo(limit) <= 0; a = a.add(BigInteger.ONE)) {              
        BigInteger copas3 = a.multiply(n1); 
        BigInteger copas7 = a.multiply(n2);

        System.out.println( copas3 );
        System.out.println( copas7 );      
    }
}

See working on repl: link

I need only the numbers that are repeated between the two formulas to be printed. So, just:

21
42
63
84
105
126
147
    
asked by anonymous 13.02.2018 / 02:40

1 answer

2

A pretty simple solution is to use two variables in for one for copas3 and one for copas7 , instead of being the a variable for both. So it can always increase to the one that is lower to give the possibility of both being equal:

public static void main(String[] args) {

    BigInteger start = new BigInteger("1");
    BigInteger limit = new BigInteger("50");
    BigInteger n1 = new BigInteger("3");
    BigInteger n2 = new BigInteger("7");

    for (BigInteger a=start,b=start;a.compareTo(limit)<=0 && b.compareTo(limit) <= 0;){ 
        BigInteger copas3 = a.multiply(n1); //contador "a" apenas para o copas3
        BigInteger copas7 = b.multiply(n2); //contador "b" apenas para o copas7

        int comparacao = copas3.compareTo(copas7); 
        if (comparacao == 0) { //escreve apenas se forem iguais
            System.out.println(copas3);
        }

        //aumenta apenas o mais pequeno
        if (comparacao <= 0) { 
            a = a.add(BigInteger.ONE);
        }
        else {
            b = b.add(BigInteger.ONE);
        }
    }
}

See the result you were looking for in Ideone

    
13.02.2018 / 04:36