I was playing around with this compile time implementation.
I use ttmath.org in order to handle large numbers. ttmath::UInt<SIZE>
works well for run time fib()
function but
I don't know how I can handle large big numbers for my meta functions since I have to change the non template parameter size_t
.
#include <iostream>
#include <omp.h>
#include <ctime>
#include "ttmath/ttmath.h"
#include <type_traits>
#define SIZE 1090
// how can I use ttmath here ?
template<size_t N>
struct fibonacci : std::integral_constant<size_t, fibonacci<N-1>{} + fibonacci<N-2>{}> {};
template<> struct fibonacci<1> : std::integral_constant<size_t,1> {};
template<> struct fibonacci<0> : std::integral_constant<size_t,0> {};
// ttmath here works well at run time !
ttmath::UInt<SIZE> fib(size_t n)
{
ttmath::UInt<SIZE> a,b,c;
a = 1, b = 1;
for (size_t i = 3; i <= n; i++) {
ttmath::UInt<SIZE> c = a + b;
a = b;
b = c;
}
return b;
}
int main() {
const size_t N = 500;
if(1)
{
clock_t start = clock();
std::cout << "Fibonacci(" << N << ") = " << fib(N) << std::endl;
std::cout << "Time : " << (double)(clock() - start)/CLOCKS_PER_SEC << " s" << std::endl;
}
if(1)
{
clock_t start = clock();
std::cout << "Fibonacci(" << N << ") = " << fibonacci<N>() << std::endl;
std::cout << "Time : " << (double)(clock() - start)/CLOCKS_PER_SEC << " s" << std::endl;
}
}
Result is :
Fibonacci(500) = 139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125
Time : 0.003006 s
Fibonacci(500) = 2171430676560690477
Time : 1.5e-05 s
So is it possible to provide ttmath for the meta fibonacci easily ? Or should I do things differently ?