Jump to content

Fibonacci sequence: Difference between revisions

Added C++ versions
(→‎{{header|D}}: Fixed English)
(Added C++ versions)
Line 37:
00:.1:.>:"@"8**++\1+:67+`#@_v
^ .:\/*8"@"\%*8"@":\ <
 
=={{header|C++}}==
Using unsigned int, this version only works up to 48 before fib overflows.
<cpp>#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;
}
</cpp>
 
{{libheader|GMP}}
This version does not have an upper bound.
 
<cpp>#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;
}</cpp>
 
=={{header|D}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.