sunfresh

Fibonacci

Jan 20th, 2023
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. Fibonacci
  2. 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.
  3.  
  4. Input
  5. On the first line you will be given n.
  6.  
  7. Output
  8. On the only output line you should print fib(n)
  9.  
  10. Constraints
  11. n>=0
  12.  
  13. Sample tests
  14. Input
  15. 0
  16. Output
  17. 0
  18. Input
  19. 1
  20. Output
  21. 1
  22. Input
  23. 7
  24. Output
  25. 13
  26.  
  27.  
  28. import java.util.Scanner;
  29.  
  30. public class Fibonacci {
  31. public static void main(String[] args) {
  32. Scanner scanner = new Scanner(System.in);
  33. int n = scanner.nextInt();
  34. long[] numbers = new long[n + 1];
  35. System.out.println(fib(n, numbers));
  36. }
  37.  
  38. static long fib(int n, long[] numbers) {
  39. if (numbers[n] == 0) {
  40. if (n < 2) {
  41. return n;
  42. }
  43. numbers[n] = fib(n - 1, numbers) + fib(n - 2, numbers);
  44. }
  45. return numbers[n];
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment