Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- // Generate any fibonacci number
- // from the 1st to the 47th
- // The data type unsigned is 4 bytes.
- int main()
- {
- unsigned which_fibonacci = 0; // Which number to show.
- unsigned first = 0; // First number in the sum.
- unsigned second = 1; // Second number in the sum.
- unsigned next = 1; // Current sum (fibonacci number).
- unsigned final_fibonacci = 0; // Result.
- cout << "Which fibonacci number would you like to see? (1 - 47)\n";
- cin >> which_fibonacci; // Get user request.
- // Only numbers in position 1 to 47 can be displayed with 4 bytes.
- // If the user request is outside that range,
- while ( (which_fibonacci < 1) || (which_fibonacci > 47) )
- {
- cout << "Please choose a number from 1 to 47\n";
- cin >> which_fibonacci; // Get new request.
- }
- // If the first or second fibonacci number is requested,
- if (which_fibonacci == 1 || which_fibonacci == 2)
- {
- final_fibonacci = 1; // It is 1.
- }
- else // If the third or greater fibonacci number is requested,
- {
- // Do the computation the proper number of times.
- for (int i = 1; i <= (which_fibonacci - 2); ++i)
- {
- // Shift the addition to the last two
- // fibonacci numbers.
- first = second;
- second = next;
- next = first + second; // Calculate the next number.
- }
- final_fibonacci = next; // This is the result.
- }
- cout << "Fibonacci number " << which_fibonacci << " is " << final_fibonacci << '\n';
- // End the program.
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement