Java 将长方法转换为BigInteger方法
我有两种使用Java 将长方法转换为BigInteger方法,java,biginteger,Java,Biginteger,我有两种使用long的方法,我想改用biginger: 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) { lo
long
的方法,我想改用biginger:
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;
}
当我使用这些方法并在我的程序中运行它们时,它似乎卡住了,无法工作。我一直在想到底是怎么回事,但还是弄不明白。有什么建议吗?谢谢 j.add(biginger.valueOf(1))
不会更改j
。它返回一个新的biginger
,其值比j
多一个,但您将丢弃它。尝试j=j.add(biginger.ONE)
[此常量是为您提供的,因此您不必键入valueOf(1)
]
事实上,
biginger
(就像String
)是一种不可变类型,这意味着没有方法可以更改biginger
对象的内容,只有方法可以返回新的biginger
对象。是的,它起作用了。我知道问题在于无限循环,但我不知道为什么。BigInteger对象是不可变的类型,这是有道理的。谢谢
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;
}