Fibonacci sequence 纪中 1240 矩阵乘法

这里写图片描述

分析

这就是裸的矩阵乘法啊!!!
数列f[n]=f[n-1]+f[n-2],f[1]=f[2]=1的前n项和s[n]的快速求法
0 1 0
1 1 1
0 0 1

代码

const
  a1:array[1..3,1..3] of int64=((0,1,0),
                                (1,1,1),
                                (0,0,1));
  f:array[1..3] of int64=(1,1,1);

type
  arr=array[1..3,1..3] of int64;

var
  a:arr;
  b:array[1..10] of int64;
  i,j,k:longint;
  n,n1:int64;
  m:longint;
  ans:longint;

function cheng(x,x1:arr):arr;
var
  i,j,k:longint;
begin
  fillchar(cheng,sizeof(cheng),0);
  for i:=1 to 3 do
    for j:=1 to 3 do
      for k:=1 to 3 do
        cheng[i,j]:=(cheng[i,j]+x[i,k]*x1[k,j]) mod 10000;
end;

function seach(n:int64):arr;
var
  i,j,k:longint;
  an:arr;
begin
  fillchar(an,sizeof(an),0);
  if n<>1
    then
      if n mod 2=0
        then begin
               an:=seach(n div 2);
               seach:=cheng(an,an);
             end
        else begin
               an:=seach(n div 2);
               an:=cheng(an,an);
               seach:=cheng(an,a1);
             end
    else
      seach:=a1;
end;

begin
  readln(m);
  for i:=1 to m do begin
    read(n,n1);
    n:=n-2; n1:=n1-1;
    ans:=0;
    fillchar(b,sizeof(b),0);
    if n>0 then begin
      a:=seach(n);
      for j:=1 to 3 do
        for k:=1 to 3 do
          b[j]:=(b[j]+f[k]*a[k,j]) mod 10000;
      ans:=b[3] mod 10000;
    end
    else if n<>-1 then ans:=1;
    n:=n1;
    fillchar(b,sizeof(b),0);
    if n>0 then begin
      a:=seach(n);
      for j:=1 to 3 do
        for k:=1 to 3 do
          b[j]:=(b[j]+f[k]*a[k,j]) mod 10000;
      ans:=b[3] mod 10000-ans;
    end
    else if n<>-1 then ans:=1-ans;
    if ans<0 then ans:=ans+10000;
    writeln(ans);
  end;
end.

posted @ 2016-07-12 17:07  一个响亮的蒟蒻  阅读(135)  评论(0编辑  收藏  举报