求斐波那契数列log(n) pascal算法程序

问题描述:

求斐波那契数列log(n) pascal算法程序
如题,注意是Log(n)
1个回答 分类:综合 2014-10-04

问题解答:

我来补答
用矩阵加速
[ f(n+1) ] [1 1] [ f(n) ]
=
[ f(n) ] [1 0] [ f(n-1)]
不停的迭代就行了
递归求解,log(n)的
program fibonacci;
type
matrix=array[1..2,1..2] of qword;
var
c,cc:matrix;
n:integer;
function multiply(x,y:matrix):matrix;
var
temp:matrix;
begin
temp[1,1]:=x[1,1]*y[1,1]+x[1,2]*y[2,1];
temp[1,2]:=x[1,1]*y[1,2]+x[1,2]*y[2,2];
temp[2,1]:=x[2,1]*y[1,1]+x[2,2]*y[2,1];
temp[2,2]:=x[2,1]*y[1,2]+x[2,2]*y[2,2];
exit(temp);
end;
function getcc(n:integer):matrix;
var
temp:matrix;
t:integer;
begin
if n=1 then exit(c);
t:=n div 2;
temp:=getcc(t);
temp:=multiply(temp,temp);
if odd(n) then exit(multiply(temp,c))
else exit(temp);
end;
procedure init;
begin
readln(n);
c[1,1]:=1;
c[1,2]:=1;
c[2,1]:=1;
c[2,2]:=0;
if n=1 then
begin
writeln(1);
halt;
end;
if n=2 then
begin
writeln(1);
halt;
end;
cc:=getcc(n-2);
end;
procedure work;
begin
writeln(cc[1,1]+cc[1,2]);
end;
begin
init;
work;
end.
 
 
展开全文阅读
剩余:2000