离散数论知识点:
(a+b)%c = (a%c)+(b%c)
(a*b)%c = ((a%c)*(b%c))%c
快速幂:
int quickpow(int m,int n,int k){
int b = 1;
while(n>0){
if(n & 1)
b = (b*m)%k;
n = >>1;
m = (m*m)%k;
}
return b;
}
求斐波拉契数列的某项的前四位和后四位:
#include <iostream>
#include <cstdio>
#include <cmath>
#define Mod 10000
using namespace std;
const int MAX=2;
long long f[100];
typedef struct {
int m[MAX][MAX];
}MATRIX;
MATRIX P = {0,1,1,1};
MATRIX I = {1,0,0,1};
//矩阵相乘
MATRIX matrixmul(MATRIX a,MATRIX b){
int i,j,k;
MATRIX c;
for(i=0;i<MAX;i++){
for(j=0;j<MAX;j++){
c.m[i][j] = 0;
for(k=0;k<MAX;k++){
c.m[i][j] += (a.m[i][k]*b.m[k][j])%Mod;
}
c.m[i][j] %= Mod;
}
}
return c;
}
//矩阵的快速幂
MATRIX quickpow(long long n){
MATRIX b = I;
MATRIX m = P;
while(n>0){
if(n&1)
b = matrixmul(b,m);
n = n>>1;
m = matrixmul(m,m);
}
return b;
}
int main()
{
double log_s = 0.0;
MATRIX temp;
int n,i,bit=0;
f[0]=0;
f[1]=1;
for(i=2;i<=50;i++){
f[i] = f[i-1]+f[i-2];
if(f[i]>100000000){
bit=i-1;
break;
}
}
while(cin>>n){
if(n<=bit)
cout<<f[n]<<endl;
if(n>bit){
temp = quickpow(n);
int last_bit = temp.m[0][1];
log_s=log10(1.0/sqrt(5)) +(double)n*log10((1.0+sqrt(5))/2.0);
int ans_s=(int)(pow(10,log_s-(int)log_s+3));
cout<<ans_s<<"...";
printf("%04d\n",last_bit);
}
}
return 0;
}