Issue
I am trying to create a program which will generate numbers in the Fibonacci sequence until it finds a 1,000 digit number which is in the sequence. The code I have used runs fine and give a valid output, however, I have had trouble retrieving the length of each number; using BigInteger
I have converted the BigInteger
to a String
and used the String.length()
method to get the length, however, I have found that this is not giving the real length, and I can not see why.
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());
}
}
Is there a better way to get the length of a BigInteger
? I have alread reffered to the question thBigInteger: count the number of decimal digits in a scalable method
Update Text text which is outputted after running the program is:
The first term in the Fibonacci sequence to contain 1,000 digits is term: 4781
We know this is false because if we look at the project I am attempting, when we input 4781 as the answer, it is incorrect. Click here to view the project (Project Euler - Problem 25)
Solution
When this code is executed (i.e. the solution is found):
if ((tempAns.toString().length()) == 1000)
{
fibonacciNumbers.add(tempAns);
validNo = false;
break;
}
The tempAns is not printed. That's why your last printed number is only 999 digits long.
If you add a System.out.println("and is: " + tempAns);
at the end, just before the end of the main method you will get the desired number. And the answer is thus 4781 + 1 = 4782
Answered By - Burkhard
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)