用矩阵求斐波那契数列,快速幂log(n),只用求最后4位(加和乘的运算中前面的位数无用)

 #include <stdio.h>
#include <stdlib.h> int main()
{
/*
(x y)(x y)= (x*x+y*s x*y+y*t) =(x*x+y*s y*(x+t))
(s t)(s t) (s*x+t*s s*y+t*t) (s*(x+t) t*t+y*s)
(x y)(a b)= (x*a+y*c x*b+y*d)
(s t)(c d) (s*a+t*c s*b+t*d)
(a b)(f1=1)=(a+b)
(c d)(f2=1) (c+d)
*/
//(a,b)(c,d)一开始为E2
long n,x,y,s,t,xx,yy,ss,tt,a,b,c,d,aa,bb,cc,dd;
while (scanf("%ld",&n))
{
if (n==)
{
printf("0\n");
continue;
}
else if (n==-)
break;
n-=;
x=;
y=;
s=;
t=;
a=;
b=;
c=;
d=;
while (n)
{
if (n%==)
{
aa=a;
bb=b;
cc=c;
dd=d;
a=(x*aa+y*cc)%;
b=(x*bb+y*dd)%;
c=(s*aa+t*cc)%;
d=(s*bb+t*dd)%;
}
xx=x;
yy=y;
ss=s;
tt=t;
x=(xx*xx+yy*ss)%;
y=(yy*(xx+tt))%;
s=(ss*(xx+tt))%;
t=(tt*tt+yy*ss)%;
n=n/;
}
printf("%ld\n",(c+d)%);
} return ;
}
 #include <stdio.h>
#include <stdlib.h> int main()
{
/*
(x y)(x y)= (x*x+y*s x*y+y*t) =(x*x+y*s y*(x+t))
(s t)(s t) (s*x+t*s s*y+t*t) (s*(x+t) t*t+y*s)
(x y)(a b)= (x*a+y*c x*b+y*d)
(s t)(c d) (s*a+t*c s*b+t*d)
(a b)(f1=1)=(a+b)
(c d)(f2=1) (c+d)
*/
//(a,b)(c,d)一开始为E2
long n,x[],y[],s[],t[],a[],b[],c[],d[],w,r,i;
x[]=;
y[]=;
s[]=;
t[]=;
a[]=;
b[]=;
c[]=;
d[]=;
for (i=;i<;i++)
{
x[i]=(x[i-]*x[i-]+y[i-]*s[i-])%;
y[i]=(y[i-]*(x[i-]+t[i-]))%;
s[i]=(s[i-]*(x[i-]+t[i-]))%;
t[i]=(t[i-]*t[i-]+y[i-]*s[i-])%;
}
while (scanf("%ld",&n))
{
if (n==)
{
printf("0\n");
continue;
}
else if (n==-)
break;
n-=;
w=;
r=;
while (n)
{
if (n%==)
{
a[r+]=(x[w]*a[r]+y[w]*c[r])%;
b[r+]=(x[w]*b[r]+y[w]*d[r])%;
c[r+]=(s[w]*a[r]+t[w]*c[r])%;
d[r+]=(s[w]*b[r]+t[w]*d[r])%;
r++;
}
w++;
n=n/;
}
printf("%ld\n",(c[r]+d[r])%);
}
return ;
}
05-11 22:22