【Description】
【Solution】
矩阵快速幂。递推式:
⎡⎣⎢10k00110111⎤⎦⎥⎡⎣⎢f[i−1]i−11⎤⎦⎥=⎡⎣⎢f[i]i1⎤⎦⎥
代码如下:
/**************************************************************
Problem: 2326
User: llgyc
Language: Pascal
Result: Accepted
Time:56 ms
Memory:224 kb
****************************************************************/
type matrix = array[1..3,1..3] of qword;
var n,m,base:qword;
ans,t:matrix;
i:longint;
function mul(x,y:qword):qword;
var tmp:qword;
begin
tmp:=0;
while (y>0) do begin
if (y mod 2=1) then tmp:=(tmp+x) mod m;
x:=(x*2) mod m; y:=y div 2;
end; exit(tmp);
end;
procedure multi(var a,b,c:matrix);
var i,j,k:longint;
tmp:matrix;
begin
fillchar(tmp,sizeof(tmp),0);
for i:=1 to 3 do
for j:=1 to 3 do
for k:=1 to 3 do
tmp[i,j]:=(tmp[i,j]+mul(a[i,k],b[k,j])) mod m;
c:=tmp;
end;
procedure cal(base,last:qword);
var tmp:qword;
i,j:longint;
begin
fillchar(t,sizeof(t),0);
t[1,1]:=base; t[1,2]:=1; t[1,3]:=1; t[2,2]:=1; t[2,3]:=1; t[3,3]:=1;
tmp:=last-base div 10+1;
while (tmp>0) do begin
if (tmp mod 2=1) then multi(t,ans,ans);
multi(t,t,t); tmp:=tmp div 2;
end;
end;
begin
readln(n,m); for i:=1 to 3 do ans[i,i]:=1;
base:=10;
while (n>=base) do begin cal(base,base-1); base:=base*10; end; cal(base,n);
writeln(ans[1,3]);
end.