TheAlgorithms-C-Plus-Plus/math/fibonacci.cpp

36 lines
789 B
C++
Raw Normal View History

2020-05-28 03:42:23 +08:00
/**
* @file
* @brief Generate fibonacci sequence
*
* Calculate the the value on Fibonacci's sequence given an
* integer as input.
* \f[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\f]
2020-05-28 05:58:17 +08:00
*
2020-05-29 03:19:27 +08:00
* @see fibonacci_large.cpp, fibonacci_fast.cpp, string_fibonacci.cpp
2020-05-28 03:42:23 +08:00
*/
#include <cassert>
2020-05-26 10:13:52 +08:00
#include <iostream>
2020-05-28 03:42:23 +08:00
/**
* Recursively compute sequences
*/
int fibonacci(unsigned int n)
{
/* If the input is 0 or 1 just return the same
This will set the first 2 values of the sequence */
2020-05-28 05:58:17 +08:00
if (n <= 1)
return n;
/* Add the last 2 values of the sequence to get next */
2020-05-26 10:13:52 +08:00
return fibonacci(n - 1) + fibonacci(n - 2);
}
2020-05-28 03:42:23 +08:00
/// Main function
int main()
{
int n;
std::cin >> n;
assert(n >= 0);
std::cout << "F(" << n << ")= " << fibonacci(n) << std::endl;
}