سؤال

BigInteger n = BigInteger.valueOf(5);
BigInteger a = BigInteger.valueOf(3);
System.out.println(a.gcd(n) != BigInteger.ONE);

Why does this evaluate as true even though 5 and 3's gcd is 1?

هل كانت مفيدة؟

المحلول

You should not use the != operator, but instead use the equals() method

!(a.gcd(n).equals(BigInteger.ONE))

Explanation:

In Java, the == and != operators, when used on objects, compare if the variables are references to the same exact object in memory, not if the objects have the same value. The equals() method checks if they have the same value.

نصائح أخرى

Since BigInteger is an object, you should rather use equals. You use == or != to compare reference of the objects.

!(a.gcd(n).equals(BigInteger.ONE));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top