2016-09-11 34 views
1

由于某种原因,我的val变量在while循环内没有增加。任何理由为什么它不这样做? val.add(BigInteger.ONE);BigInteger不增加?

import java.math.*; 

public static void main(String[] args) { 

    /* Variables */ 
    BigInteger PQ = new BigInteger("17"); 
    BigInteger E = new BigInteger("7"); 

    BigInteger val = new BigInteger("2"); 

    /* Find the PRIME factors of PQ */ 
    while (PQ.compareTo(BigInteger.ONE) == 1) { // while the first value is greater 
     if (PQ.mod(val).equals(BigInteger.ZERO)) { 
      System.out.print(val + " "); 
     } else { 
      val.add(BigInteger.ONE); 
     } 
    } 
} 
+1

虽然['BigInteger.compareTo(的BigInteger VAL)'](https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#compareTo-java.math .BigInteger-)将返回值明确地列出为*“ - 1,0或1”*,最好是对从Comparable继承的更一般的契约进行编码,该契约表示*“一个负整数,零或一个正整数” *,所以你应该写'a.compareTo(b)> 0'而不是'a.compareTo(b)== 1'。它也读得更好,因为它意味着'a> b',即'a.compareTo(b)OP 0'意味着'一个OP b',其中'OP'可以''',''''' ,或'!='。 – Andreas

回答

7

val.add(BigInteger.ONE)返回一个新值。你不把它分配给什么:

val = val.add(BigInteger.ONE); 

Class BigInteger

+0

哇。甚至没有意识到这一点。谢谢! – Dandy

+1

也注意到:这不是一个有效的方法来分解大数字。 –

+0

“效率不高”可以重新编为“不切实际效率低下”..... –

0

您可以重新初始化的总和。

BigInteger val=BigInteger.valueOf(10); 
BigInteger val2=BigInteger.valueOf(20); 
BigInteger val3=va1.add(val2);