【发布时间】:2015-10-08 21:15:08
【问题描述】:
我在玩这个compile time implementation。
我使用ttmath.org 来处理大量数字。 ttmath::UInt<SIZE> 适用于运行时 fib() 函数,但是
我不知道如何为我的元函数处理大数字,因为我必须更改非模板参数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;
}
}
结果是:
斐波那契(500) = 139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125
时间:0.003006 秒
斐波那契 (500) = 2171430676560690477
时间:1.5e-05 s
那么是否可以轻松地为元斐波那契提供 ttmath ?还是我应该做不同的事情?
【问题讨论】:
-
因为 ttmath 可以处理大于 size_t 的数字,但 fibbonachi
会尝试读取 size_t,这在您的系统上可能是 64 位,而您无法将 105 位数字放入 64 位 -
是的,我知道为什么。我想知道如何解决这个问题。
标签: c++ metaprogramming fibonacci