Advertisement
janac

Calculate Fibonacci number

Dec 6th, 2021
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Generate any fibonacci number
  5. // from the 1st to the 47th
  6. // The data type unsigned is 4 bytes.
  7. int main()
  8. {
  9.     unsigned which_fibonacci = 0; // Which number to show.
  10.     unsigned first = 0; // First number in the sum.
  11.     unsigned second = 1; // Second number in the sum.
  12.     unsigned next = 1; // Current sum (fibonacci number).
  13.     unsigned final_fibonacci = 0; // Result.
  14.  
  15.     cout << "Which fibonacci number would you like to see? (1 - 47)\n";
  16.     cin >> which_fibonacci; // Get user request.
  17.     // Only numbers in position 1 to 47 can be displayed with 4 bytes.
  18.     // If the user request is outside that range,
  19.     while ( (which_fibonacci < 1) || (which_fibonacci > 47) )
  20.     {
  21.         cout << "Please choose a number from 1 to 47\n";
  22.         cin >> which_fibonacci; // Get new request.
  23.     }
  24.  
  25.     // If the first or second fibonacci number is requested,
  26.     if (which_fibonacci == 1 || which_fibonacci == 2)
  27.     {
  28.         final_fibonacci = 1; // It is 1.
  29.     }
  30.     else // If the third or greater fibonacci number is requested,
  31.     {
  32.         // Do the computation the proper number of times.
  33.         for (int i = 1; i <= (which_fibonacci - 2); ++i)
  34.         {
  35.             // Shift the addition to the last two
  36.             // fibonacci numbers.
  37.             first = second;
  38.             second = next;
  39.             next = first + second; // Calculate the next number.
  40.         }
  41.  
  42.         final_fibonacci = next; // This is the result.
  43.     }
  44.  
  45.     cout << "Fibonacci number " << which_fibonacci << " is " << final_fibonacci << '\n';
  46.  
  47.     // End the program.
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement