fork(1) download
  1. /* Compile time Fibonacci calculation. Inspired by
  2. http://e...content-available-to-author-only...2.com/title/C%252B%252B%253A+computing+Fibonacci+numbers+at+compile+time */
  3.  
  4. typedef long long unsigned int Number;
  5.  
  6. template<Number N> struct Fibonacci
  7. {
  8. static const Number Value = Fibonacci<N-1>::Value + Fibonacci<N-2>::Value ;
  9.  
  10. };
  11.  
  12. template<>
  13. struct Fibonacci<0>
  14. {
  15. static const Number Value = 0;
  16. };
  17.  
  18. template<>
  19. struct Fibonacci <1>
  20. {
  21. static const Number Value = 1;
  22. };
  23.  
  24.  
  25. #include <iostream>
  26. int main()
  27. {
  28. // note: for integers maximum value is: 2147483647
  29. // but here it's long long unsigned which means our maximum will be just short of Fibonacci 94
  30. // the Fibonacci numbers can be verified here
  31. // http://w...content-available-to-author-only...c.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
  32.  
  33. std::cout << "Fibonacci (84) = " << Fibonacci<84>::Value<< std::endl;
  34. std::cout << "Fibonacci (92) = " << Fibonacci<92>::Value<< std::endl;
  35. std::cout << "Fibonacci (93) = " << Fibonacci<93>::Value<< std::endl;
  36. std::cout << "Fibonacci (94) = " << Fibonacci<94>::Value<< "/* error long long unsigned overflow *\ " << std::endl;
  37.  
  38. std::cout << "\n\nMax value LLU: \t " << Number(0)-1 << std::endl;
  39. std::cout <<"Fibonacci 94\t 19740274219868223167 \naccording to www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html" ;
  40. return 0;
  41. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
Fibonacci (84) = 160500643816367088
Fibonacci (92) = 7540113804746346429
Fibonacci (93) = 12200160415121876738
Fibonacci (94) = 1293530146158671551/* error long long unsigned overflow * 


Max value LLU: 	 18446744073709551615
Fibonacci 94	 19740274219868223167 
according to www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html