Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Fibonacci
- The Fibonacci sequence is a famous bit of mathematics, and it happens to have a recursive definition. The first two values in the sequence are 0 and 1 (essentially 2 base cases). Each subsequent value is the sum of the previous two values, so the whole sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. Define a recursive fibonacci(n) method that returns the nth Fibonacci number, with n=0 representing the start of the sequence.
- Input
- On the first line you will be given n.
- Output
- On the only output line you should print fib(n)
- Constraints
- n>=0
- Sample tests
- Input
- 0
- Output
- 0
- Input
- 1
- Output
- 1
- Input
- 7
- Output
- 13
- import java.util.Scanner;
- public class Fibonacci {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int n = scanner.nextInt();
- long[] numbers = new long[n + 1];
- System.out.println(fib(n, numbers));
- }
- static long fib(int n, long[] numbers) {
- if (numbers[n] == 0) {
- if (n < 2) {
- return n;
- }
- numbers[n] = fib(n - 1, numbers) + fib(n - 2, numbers);
- }
- return numbers[n];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment