Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将长方法转换为BigInteger方法_Java_Biginteger - Fatal编程技术网

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;
}