Advertisement
coffeebeforecode

CSE2012 PP2 Q2

Aug 12th, 2021
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. /*
  2. 2. In 1202, Fibonacci introduced the sequence to Western European mathematics. Consider the
  3. Fibonacci sequence.
  4. where, F0 = 0, F1 = 1.
  5. 0, 1, 1, 2, 3, 5, 8, 13, 21, . . .
  6. 1. Write a procedure to find Fn using recursive definition of the Fibonacci numbers. Discuss
  7. the time complexity of the algorithm.
  8. 2. Write a iterative procedure to find Fn. Discuss the time complexity of the algorithm.
  9. 3. Design an efficient procedure to find Fn using Binet’s formula. Discuss the time complexity
  10. and implementation issue if any.
  11. */
  12.  
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <math.h>
  16.  
  17. long long recFib(int n){
  18. int f0 = 0;
  19. int f1 = 1;
  20. if (n <= 0){
  21. return f0;
  22. }
  23. if (n == 1){
  24. return f1;
  25. }
  26.  
  27. return recFib(n-1)+recFib(n-2);
  28. }
  29.  
  30. long long iterFib(int n){
  31. int f0 = 0;
  32. int f1 = 1;
  33. int k;
  34. if (n <= 0){
  35. return f0;
  36. }
  37. if (n == 1){
  38. return f1;
  39. }
  40.  
  41. int i;
  42.  
  43. for(i = 2; i <= n; i++){
  44. k = f1+f0;
  45. f0 = f1;
  46. f1 = k;
  47. }
  48.  
  49. return k;
  50.  
  51. }
  52.  
  53. long long binetFib(int n){
  54. long long a = (pow((1+sqrt(5))/2, n) - pow((1-sqrt(5))/2, n)) / sqrt(5);
  55. return a;
  56. }
  57.  
  58. int main(){
  59. int ch, n;
  60. while(1){
  61. printf("\nProgram to Print the nth Fibonacci number");
  62. printf("\n\tMENU\n");
  63. printf("\n1. Recursive");
  64. printf("\n2. Iterative");
  65. printf("\n3. Binet's formula");
  66. printf("\n4. Exit");
  67. printf("\n>>");
  68. scanf("%d", &ch);
  69.  
  70. if (ch == 4){
  71. exit(0);
  72. }
  73.  
  74. printf("\nInput n: ");
  75. scanf("%d", &n);
  76. printf("\nAns: ");
  77.  
  78. switch (ch)
  79. {
  80. case 1:
  81. printf("%lld\n", recFib(n));
  82. break;
  83. case 2:
  84. printf("%lld\n", iterFib(n));
  85. break;
  86. case 3:
  87. printf("%lld\n", binetFib(n));
  88. break;
  89. default:
  90. printf("\nWrong Choice, try again!\n");
  91. break;
  92. }
  93. }
  94. return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement