[ create a new paste ] login | about

Link: http://codepad.org/Ve7pvSjP    [ raw code | output | fork ]

jfs - C++, pasted on Dec 3:
// $ g++ -std=c++0x -Wall alec.cpp -o alec && ./alec
#include <stdint.h> // uint64_t
#include <iostream>

namespace {

uint64_t fibonacci(int n)
{
  static uint64_t f[94] = { 0, 1 };
  const int size = sizeof(f)/sizeof(*f);

  if (n <= 0 or n > size)
    return -1;//return some invalid number to tell the caller that he used bad input

  if (n != 1 and f[n-1] == 0)
    for (int i = 2; i < size; i++) // compute all values at once
      f[i] = f[i-2] + f[i-1];    

  return f[n-1]; // return n-th fibonacci number
}

  template<unsigned N>
  struct Fibonacci {
    static const uint64_t value = Fibonacci<N-1>::value + Fibonacci<N-2>::value;
  };

  template<> struct Fibonacci<0> {
    static const uint64_t value = 0;
  };

  template<> struct Fibonacci<1> {
    static const uint64_t value = 1;
  };

}
int main()
{
  for (int i = 0; i < 8; ++i)
    std::cout << fibonacci(i) << " ";
  std::cout << "\n";
  std::cout << "7:   " << fibonacci(7) << " " << Fibonacci<6>::value << std::endl;
  std::cout << "94: " << fibonacci(94) << " " << Fibonacci<93>::value << std::endl;
}


Output:
1
2
3
18446744073709551615 0 1 1 2 3 5 8 
7:   8 8
94: 12200160415121876738 12200160415121876738


Create a new paste based on this one


Comments: