Loading...
Loading...
Loading...
A gardener notes that the number of leaves on a plant follows the Fibonacci sequence: F(0) = 0, F(1) = 1, and every next value is the sum of the two before it (0, 1, 1, 2, 3, 5, 8, …). Print F(n).
Write a method static long fib(int n) that uses a loop.
Example 1
Input
10
Output
55
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55: F(10) is 55.
Example 2
Input
0
Output
0
Try the problem first. Open one hint at a time.
Keep two variables: the previous value and the current value.
Each step: next = prev + curr; prev = curr; curr = next;.
Return early for n = 0.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor