http://zhedahht.blog.163.com/blog/static/25411174200722991933440/
http://blog.csdn.net/foolishwolf_x/article/details/8774874
log(n)时间求a^n。
代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std;/*
f(0) = 0.
f(1) = 1.
f(N) = f(N-1) + f(N-2)_ (N>=2)see http://blog.linjian.org/articles/fibonacci-essay/ for more detail
*/// recursive
unsigned int rfib(unsigned int n)
{// o(2^n)
if (n<2)
{
return n;
}
else
{
return rfib(n-1)+rfib(n-2);
}
}// use table to reuse value : forward
#define MAX 1000
unsigned int f[MAX]={0};
unsigned int tfib_forward(unsigned int n)
{// o(n)
f[0] = 0;
f[1] = 1;
for (unsigned int i=2;i<=n;++i)
{
f[i] = f[i-1] + f[i-2];
}
return f[n];
}// use table to reuse value : backward
unsigned int tfib_backward(unsigned int n)
{
if (n<2)
{
f[n] = n;
return f[n];
}
else
{
if(f[n]==0)
f[n] = tfib_backward(n-1) + tfib_backward(n-2);
return f[n];
}
}// use temp value instead of table
unsigned int fib(unsigned int n)
{// o(n)
if (n<2)
{
return n;
}
else
{
unsigned int a=0,b=1,c;
for (unsigned int i=2;i<=n;++i)
{
c = a + b;
a = b;
b = c;
}
return c;
}
}// use template meta programming #1 struct-enum
// enum has value range
#define FIBE(N) FibE<N>::Valtemplate<int N>
struct FibE
{
enum
{
Val = FibE<N-1>::Val + FibE<N-2>::Val
};
};template<>
struct FibE<0>
{
enum
{
Val = 0
};
};template<>
struct FibE<1>
{
enum
{
Val = 1
};
};// use template meta programming # class-static const
#define FIBC(N) FibC<N>::valtemplate<int N>
class FibC
{
public:
static const unsigned int val = FibC<N-1>::val + FibC<N-2>::val;
};template<>
class FibC<0>
{
public:
static const unsigned int val = 0;
};template<>
class FibC<1>
{
public:
static const unsigned int val = 1;
};// use calss-function
class Fib
{
public:
Fib() : a(0), b(1), n(0)
{
}
unsigned int operator()()
{
if (n <= 1) {
n++;
return n - 1;
} else {
int c;
c = a + b;
a = b;
b = c;
return c;
}
}
private:
int a, b, n;
};// test
void test_tfib_forward()
{
for (int i=0;i<MAX;++i)
{
cout<< tfib_forward(i)<<" ";
}
}void test_metaFibE()
{
cout<<FIBE(50)<<endl;
}void test_metaFibC()
{
cout<<FIBC(50)<<endl;
}void test_cfib()
{
int i=10;
Fib fib;
do {
cout << fib() << endl;
} while (i--);
}int main()
{
//test_tfib_forward();
test_metaFibE();
test_metaFibC();
test_cfib();system("pause");
return 0;
}
16.O(logn)求Fibonacci数列