Search code examples
javafunctionbigintegergreatest-common-divisor

product of GCD numbers using BigInteger


// I want to know whats wrong with this code.

public class Solution {

    public static BigInteger findGCD(BigInteger number1, BigInteger number2) {
        if(number2.intValue() == 0){
            return number1;
        }
        return findGCD(number2, number1.mod(number2));
    }

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        BigInteger i,j;
        BigInteger pro = new BigInteger("1");
        Scanner in = new Scanner(System.in);
        BigInteger N = in.nextBigInteger();
        BigInteger M = in.nextBigInteger();
        BigInteger one = new BigInteger("1");
        for(i=one;i.equals(N);i.add(one)){
            for(j=one;j.equals(M);j.add(one)){
                BigInteger a = findGCD(i,j);

                pro = pro.multiply(a);
                System.out.println(pro);
            }
        }
        System.out.println(pro);
    }
}

//I want to find out the products of GCD outputed .


Solution

  • I can see three mistakes.

    Firstly, if(number2.intValue() == 0) should be if(number2.equals(BigInteger.ZERO)). This is because intValue() only looks at 32 bits, not the whole number.

    Secondly, i.add(one) should be i = i.add(one);. i.add(one) works out the BigInteger 1 bigger than i but it does not change the value of i.

    Thirdly, I assume you mean for(i=one;!i.equals(N);...

    Also, there is a gcd method in BigInteger class already!