Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Diego Murray
2,515 PointsProject Euler 25 - 1000 digit Fibonacci Sequence (JAVA)
Not sure what is malfunctioning here. I use recursion to create the sequence. Then I have a method that switches the int to a String to grab the length. If the length is 1000 then return, ending the recursion...
package euler25;
public class ThousandDigitFibonacci {
private static int index = 1;
private static final int stop = 1000;
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int n1 = 0;
int n2 = 1;
fibonacciSequence(n1, n2);
long endTime = System.currentTimeMillis();
System.out.println("Time: " + (endTime - startTime) + " ms");
}
public static void fibonacciSequence(int n1, int n2) {
System.out.println("F" + index + " = " + n2);
if(countDigits(n1) == 1000) {
return;
}
index++;
fibonacciSequence(n2, n1+n2);
}
public static int countDigits(int fibNum) {
int length = String.valueOf(fibNum).length();
return length;
}
}
2 Answers
Thomas Nilsen
14,957 PointsThe main reason your code is failing is because you use a datatype (int) which is waaay to small for this problem.
You need to to use java's BigInteger.
Here is a solution for your problem
Thomas Nilsen
14,957 PointsBig Integers work a little bit differently.
Check out this guide
Diego Murray
2,515 PointsDiego Murray
2,515 PointsI thought this was the problem but when I switch everything to BigInteger I cannot get it to work as well. This because of a Type Mismatch Error. (ex. BigInteger n1 = 0 AND BigInteger n2 = 1)
Diego Murray
2,515 PointsDiego Murray
2,515 PointsNever mind. Thanks for the link.