JulianJulianov

13. Recursive Fibonacci

Feb 10th, 2020
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. 3. Recursive Fibonacci
  2. The Fibonacci sequence is quite a famous sequence of numbers. Each member of the sequence is calculated from the sum of the two previous elements. The first two elements are 1, 1. Therefore the sequence goes as 1, 1, 2, 3, 5, 8, 13, 21, 34…
  3. The following sequence can be generated with an array, but that’s easy, so your task is to implement recursively.
  4. So if the function GetFibonacci(n) returns the n’th Fibonacci number we can express it using GetFibonacci(n) = GetFibonacci(n-1) + GetFibonacci(n-2).
  5. However, this will never end and in a few seconds a StackOverflow Exception is thrown. In order for the recursion to stop it has to have a “bottom”. The bottom of the recursion is GetFibonacci(2) should return 1 and GetFibonacci(1) should return 1.
  6. Input Format:
  7. • On the only line in the input the user should enter the wanted Fibonacci number.
  8. Output Format:
  9. • The output should be the n’th Fibonacci number counting from 1.
  10.  
  11.  
  12. using System;
  13.  
  14. namespace _03RecursiveFibonacci
  15. {
  16. class Program
  17. {
  18. static void Main(string[] args)
  19. {
  20. int num = int.Parse(Console.ReadLine());
  21. int[] array = new int[] { 1, 1 };
  22. int sum = 0;
  23.  
  24. switch (num)
  25. {
  26. case 1:
  27. Console.WriteLine("1");
  28. return;
  29. case 2:
  30. Console.WriteLine("1");
  31. return;
  32. }
  33.  
  34. for (int i = 2; i < num; i++)
  35. {
  36. sum = array[0] + array[1];
  37. int[] newArray = new int[] { array[1], sum };
  38.  
  39. array = newArray;
  40. }
  41. Console.WriteLine(sum);
  42. }
  43. }
  44. }
  45. /* Решение чрез Мемоизация
  46. // Top down DP: recursion + memoization
  47. private static long recursiveFibonacciWithMemoization(int n) {
  48. if (n <= 1) {
  49. return 1;
  50. }
  51.  
  52. if (memo[n] != 0) {
  53. return memo[n];
  54. }
  55.  
  56. memo[n] =
  57. recursiveFibonacciWithMemoization(n - 1) +
  58. recursiveFibonacciWithMemoization(n - 2);
  59. return memo[n];
  60. }*/
Advertisement
Add Comment
Please, Sign In to add comment