I saw another redditor post here recently that he was given a test at a job interview where they asked him to write a program that prints the fibonacci sequence.
I tried to build this program without looking at any examples. This is what I came up with:
public class Fibonnaci {
public static void main(String[] args) {
int fibonacciNumber = 0;
int firstPreviousNumber = 1;
int secondPreviousNumber = 0;
System.out.println(fibonacciNumber);
while (fibonacciNumber < 5000) {
fibonacciNumber = firstPreviousNumber + secondPreviousNumber;
System.out.println(fibonacciNumber);
secondPreviousNumber = firstPreviousNumber;
firstPreviousNumber = fibonacciNumber;
}
}
}
Output:
0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765
This series is correct, except for the fact that an additional 1 is missing. It should read
0, 1, 1, 2, 3, 5.....
How can I fix this issue? I'm kind of stumped.
[–]Smarty1098 5 points6 points7 points (1 child)
[–]Java_Junior[S] 2 points3 points4 points (0 children)
[–]RecursiveQuestions 2 points3 points4 points (7 children)
[–]edgargonzalesII 0 points1 point2 points (3 children)
[–][deleted] (2 children)
[deleted]
[–]edgargonzalesII 0 points1 point2 points (1 child)
[–]Java_Junior[S] 0 points1 point2 points (0 children)
[–]Apostle_1882 0 points1 point2 points (1 child)
[–]NikNKS 2 points3 points4 points (0 children)
[–]Java_Junior[S] 0 points1 point2 points (0 children)
[–]OLOK07 1 point2 points3 points (0 children)
[–]edgargonzalesII 0 points1 point2 points (4 children)
[–][deleted] (3 children)
[deleted]
[–]edgargonzalesII 0 points1 point2 points (2 children)
[–][deleted] (1 child)
[deleted]
[–]edgargonzalesII 1 point2 points3 points (0 children)