我正在尝试创建一个程序,该程序将在斐波那契数列中生成数字,直到找到该数列中的1000位数字为止。我使用的代码可以正常运行并提供有效的输出,但是,我在检索每个数字的长度时遇到了麻烦;使用BigInteger我已经将BigInteger转换为String并使用String.length()方法来获取长度,但是,我发现这没有给出真实的长度,我不知道为什么。

import java.util.ArrayList;
import java.math.BigInteger;
public class problemTwentyFive {
  public static void main(String [] args) {
     ArrayList<BigInteger> fibonacciNumbers = new ArrayList<BigInteger>();
     boolean validNo = true;
     int x = 2;
     BigInteger tempAns = new BigInteger(""+0);
     fibonacciNumbers.add(new BigInteger(""+x));
     fibonacciNumbers.add(new BigInteger(""+x));
     do {
      tempAns = fibonacciNumbers.get(x-1).add(fibonacciNumbers.get(x-2));
      if (tempAns.toString().length() <= 1000) {
         System.out.println(tempAns.toString().length());
         if(tempAns.toString().length() == 1000) {
            fibonacciNumbers.add(tempAns);
            validNo = false;
            break;
        } else {
           fibonacciNumbers.add(tempAns);
        }
      }
      x++;
      if (tempAns.toString().length() > 1000) {
         validNo = false;
         break;
      }
      System.out.println(tempAns);
   } while (validNo == true);
   System.out.println("The first term in the Fibonacci sequence to contain 1,000 digits is term: " + fibonacciNumbers.size());
  }
}


有没有更好的方法来获取BigInteger的长度?我已经提到了这个问题

更新资料
运行该程序后输出的文本为:

The first term in the Fibonacci sequence to contain 1,000 digits is term: 4781


我们知道这是错误的,因为如果看我正在尝试的项目,当我们输入4781作为答案时,它是不正确的。单击BigInteger: count the number of decimal digits in a scalable method查看项目(Project Euler-问题25)

最佳答案

执行此代码后(即找到解决方案):

            if ((tempAns.toString().length()) == 1000)
            {
                fibonacciNumbers.add(tempAns);
                validNo = false;
                break;
            }


tempAns未打印。这就是为什么您上一次打印的号码只有999位数字的原因。

如果在main方法的末尾添加System.out.println("and is: " + tempAns);,则将获得所需的数字。因此答案是4781 + 1 = 4782

关于java - 如何获得BigInteger的准确长度?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28605624/

10-11 22:19
查看更多