#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
#define THRESHOLD 2009
#define DEAL(x) ((x) < THRESHOLD ? (x) : (x) % THRESHOLD)
int tribonacci_v1(int n)
{
if (n <= 2)
return n == 0 ? 0 : 1;
else
{
int k =
tribonacci_v1(n - 1) + tribonacci_v1(n - 2) + tribonacci_v1(n - 3);
return DEAL(k);
}
}
int tribonacci_v2(int n)
{
int res[] = {0,1,1,2};
for (int i = 3;i <= n;i++)
{
res[3] = res[2] + res[1] + res[0];
res[3] = DEAL(res[3]);
res[0] = res[1];
res[1] = res[2];
res[2] = res[3];
}
return n <= 2 ? res[n] : res[2];
}
void MatrixMul(int res[][3],const int m1[][3],const int m2[][3])
{
int tmp[3][3];
memset (tmp, 0, sizeof(tmp));
for (int i = 0;i < 3;i++)
{
for (int j = 0;j < 3;j++)
{
for (int k = 0;k < 3;k++)
{
tmp[i][j] += m1[i][k] * m2[k][j];
}
tmp[i][j] = DEAL(tmp[i][j]);
}
}
memcpy(res, tmp, sizeof(int) * 9);
}
int tribonacci_v3(int n)
{
if (n <= 2)
return n == 0 ? 0 : 1;
int matrix[3][3] = {
4 , 3, 2,
2 , 2, 1,
1 , 1, 1};
int res[3][3] = {
1 , 0 , 0,
0 , 1 , 0,
0 , 0 , 1};
int pow = n / 3;
int index = 2 - n % 3;
while (pow != 0)
{
if (pow & 1)
MatrixMul(res, res, matrix);
MatrixMul(matrix,matrix,matrix);
pow >>= 1;
}
return DEAL(res[index][0] + res[index][1]);
}
第三种方法是最完美的,但是代码量比较大,而且容易写错。在面试的时候倒是可以拿出来show一把自己的算法功底。
转自:http://ctperson.blog.ccidnet.com/blog-htm-do-showone-type-blog-itemid-1764393-uid-282150.html