How to resolve the algorithm Fibonacci sequence step by step in the C++ programming language
How to resolve the algorithm Fibonacci sequence step by step in the C++ programming language
Table of Contents
Problem Statement
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
Write a function to generate the nth Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: support for negative n in the solution is optional.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Fibonacci sequence step by step in the C++ programming language
These provided blocks of code demonstrate various methods for computing and displaying the Fibonacci sequence.
1. Using Unsigned Integers (Overflow)
int main()
{
unsigned int a = 1, b = 1;
unsigned int target = 48;
for (unsigned int n = 3; n <= target; ++n)
{
unsigned int fib = a + b;
std::cout << "F(" << n << ") = " << fib << std::endl;
a = b;
b = fib;
}
return 0;
}
This code uses unsigned integers to calculate the Fibonacci sequence, but it does not handle integer overflow. The Fibonacci sequence grows rapidly, and for n=48, the computed value overflows the 32-bit unsigned integer limit, resulting in incorrect results.
2. Using GMP for Large Integers
int main()
{
mpz_class a = mpz_class(1), b = mpz_class(1);
mpz_class target = mpz_class(100);
for (mpz_class n = mpz_class(3); n <= target; ++n)
{
mpz_class fib = b + a;
if (fib < b)
{
std::cout << "Overflow at " << n << std::endl;
break;
}
std::cout << "F(" << n << ") = " << fib << std::endl;
a = b;
b = fib;
}
return 0;
}
This code uses the GNU Multi-Precision Library (GMP) to handle arbitrarily large integers. It calculates the Fibonacci sequence without overflow, but it requires the GMP library to be installed and linked.
3. Using Template Metaprogramming
int main(int argc, char const *argv[])
{
std::cout << fibo<12>::value << std::endl;
std::cout << fibo<46>::value << std::endl;
return 0;
}
This code uses template metaprogramming to compute Fibonacci numbers at compile time. It defines a templated class fibo
that recursively calculates the Fibonacci sequence. It uses the C++11 static constexpr feature to evaluate the Fibonacci value at compile time.
4. Using Matrix Multiplication
inline void fibmul(int* f, int* g)
{
int tmp = f[0] * g[0] + f[1] * g[1];
f[1] = f[0] * g[1] + f[1] * (g[0] + g[1]);
f[0] = tmp;
}
int fibonacci(int n)
{
int f[] = { 1, 0 };
int g[] = { 0, 1 };
while (n > 0)
{
if (n & 1) // n odd
{
fibmul(f, g);
--n;
}
else
{
fibmul(g, g);
n >>= 1;
}
}
return f[1];
}
This code uses matrix multiplication to compute Fibonacci numbers. It represents Fibonacci numbers as 2x2 matrices and performs matrix multiplications to efficiently calculate the Fibonacci sequence. This method is faster than recursive or iterative approaches for large values of n.
5. Using Zeckendorf Numbers
// Use Zeckendorf numbers to display Fibonacci sequence.
// Nigel Galloway October 23rd., 2012
int main(void) {
char NG[22] = {'1', 0};
int x = -1;
N G;
for (int fibs = 1; fibs <= 20; fibs++) {
for (; G <= N(NG); ++G)
x++;
NG[fibs] = '0';
NG[fibs + 1] = 0;
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
This code uses Zeckendorf numbers to display the Fibonacci sequence. Zeckendorf numbers represent a number as a unique sum of non-consecutive Fibonacci numbers. The code generates Zeckendorf numbers and uses them to display the Fibonacci sequence.
6. Using Standard Template Library
int main()
{
int x = 1, y = 1;
generate_n(std::ostream_iterator<int>(std::cout, " "), 21, [&]{int n = x; x = y; y += n; return n; });
return 0;
}
This code uses the Standard Template Library (STL) to generate and print the Fibonacci sequence. It uses a lambda function to generate the next Fibonacci number based on the previous two. The generate_n
function generates a sequence of 21 Fibonacci numbers and outputs them to the standard output.
Source code in the cpp programming language
#include <iostream>
int main()
{
unsigned int a = 1, b = 1;
unsigned int target = 48;
for(unsigned int n = 3; n <= target; ++n)
{
unsigned int fib = a + b;
std::cout << "F("<< n << ") = " << fib << std::endl;
a = b;
b = fib;
}
return 0;
}
#include <iostream>
#include <gmpxx.h>
int main()
{
mpz_class a = mpz_class(1), b = mpz_class(1);
mpz_class target = mpz_class(100);
for(mpz_class n = mpz_class(3); n <= target; ++n)
{
mpz_class fib = b + a;
if ( fib < b )
{
std::cout << "Overflow at " << n << std::endl;
break;
}
std::cout << "F("<< n << ") = " << fib << std::endl;
a = b;
b = fib;
}
return 0;
}
#include <algorithm>
#include <vector>
#include <functional>
#include <iostream>
unsigned int fibonacci(unsigned int n) {
if (n == 0) return 0;
std::vector<int> v(n+1);
v[1] = 1;
transform(v.begin(), v.end()-2, v.begin()+1, v.begin()+2, std::plus<int>());
// "v" now contains the Fibonacci sequence from 0 up
return v[n];
}
#include <numeric>
#include <vector>
#include <functional>
#include <iostream>
unsigned int fibonacci(unsigned int n) {
if (n == 0) return 0;
std::vector<int> v(n, 1);
adjacent_difference(v.begin(), v.end()-1, v.begin()+1, std::plus<int>());
// "array" now contains the Fibonacci sequence from 1 up
return v[n-1];
}
#include <iostream>
template <int n> struct fibo
{
enum {value=fibo<n-1>::value+fibo<n-2>::value};
};
template <> struct fibo<0>
{
enum {value=0};
};
template <> struct fibo<1>
{
enum {value=1};
};
int main(int argc, char const *argv[])
{
std::cout<<fibo<12>::value<<std::endl;
std::cout<<fibo<46>::value<<std::endl;
return 0;
}
#include <iostream>
inline void fibmul(int* f, int* g)
{
int tmp = f[0]*g[0] + f[1]*g[1];
f[1] = f[0]*g[1] + f[1]*(g[0] + g[1]);
f[0] = tmp;
}
int fibonacci(int n)
{
int f[] = { 1, 0 };
int g[] = { 0, 1 };
while (n > 0)
{
if (n & 1) // n odd
{
fibmul(f, g);
--n;
}
else
{
fibmul(g, g);
n >>= 1;
}
}
return f[1];
}
int main()
{
for (int i = 0; i < 20; ++i)
std::cout << fibonacci(i) << " ";
std::cout << std::endl;
}
// Use Zeckendorf numbers to display Fibonacci sequence.
// Nigel Galloway October 23rd., 2012
int main(void) {
char NG[22] = {'1',0};
int x = -1;
N G;
for (int fibs = 1; fibs <= 20; fibs++) {
for (;G <= N(NG); ++G) x++;
NG[fibs] = '0';
NG[fibs+1] = 0;
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
// Use Standard Template Library to display Fibonacci sequence.
// Nigel Galloway March 30th., 2013
#include <algorithm>
#include <iostream>
#include <iterator>
int main()
{
int x = 1, y = 1;
generate_n(std::ostream_iterator<int>(std::cout, " "), 21, [&]{int n=x; x=y; y+=n; return n;});
return 0;
}
You may also check:How to resolve the algorithm Bioinformatics/base count step by step in the C++ programming language
You may also check:How to resolve the algorithm Four bit adder step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Averages/Mean time of day step by step in the Ada programming language
You may also check:How to resolve the algorithm Strip whitespace from a string/Top and tail step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Metafont programming language