Question

I have these two methods that use long that I want to use BigInteger instead:

public static long findfirstnocommon(long n) {
    long j;
    for(j = 2; j < n; j++)
        if(euclid(n,j) == 1) return j;
    return 0;
}

public static long euclid(long m, long n) { 
    while(m > 0) {
        long t = m;
        m = n % m;
        n = t;
    }
    return n;
}

These two methods work really well in the context of my program. However when I translate them to BigIntegers I get this:

  public static BigInteger findfirstnocommon(BigInteger n) {
    BigInteger j;
    for(j = BigInteger.valueOf(2); j.compareTo(n) == -1; j.add(BigInteger.valueOf(1))){
        if(euclid(n,j).compareTo(BigInteger.valueOf(1)) == 0){
            return j;
        }
    }
    return BigInteger.valueOf(0);
}

public static BigInteger euclid(BigInteger m, BigInteger n) { 
    BigInteger zero = BigInteger.valueOf(0);
    while(m.compareTo(zero) == 1) {
        BigInteger t = m;
        m = n.mod(m);
        n = t;
    }
    return n;
}

When I use them methods and run them in my program it appears to get stuck and not work. I've been trying to see what is wrong and can't figure it out. Any suggestions? Thanks.

Was it helpful?

Solution

j.add(BigInteger.valueOf(1)) does not change j. It returns a new BigInteger whose value is one more than j, but you're discarding it. Try j = j.add(BigInteger.ONE) [this constant is provided for you so you don't have to type valueOf(1)].

In fact, BigInteger (like String) is an immutable type, which means there are no methods that change the contents of a BigInteger object, only methods that return new BigInteger objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top