2015年11月2日 星期一

如何用DELPHI寫費氏數列??

費氏數列就是F(N)=F(N-1)+(N-2),F(1)=1,F(2)=1,F(3)=F(2)+F(1)=1+1=2,F(4)=F(3)+F(2)=2+1=3,F(5)=F(4)+F(3)=3+2=5以此類推.....

var
  N,i:Integer//i是多的
  T1,T2,tt:Integer//tt是暫存用的
begin
T1:=0
T2:=1//第一次計算時會需要一隻兔子
N:=10//會有10.9.8.7.6.5.4.3.2.1
while N > 0 do//N和0覺定你會有幾個數字,只有這樣所以你可以改成N=100 0=90
begin
Dec(N)//對n作累減用,當然你把>改成<時就要改成inc(N)
Memo1.Lines.Add(IntToStr(T1+T2))//AAAAAAAAAAAA
tt:=T1;//把母兔數量存起來
T1:=T2;//把子代變成母代
T2:=tt+T2//現在n的母數量//BBBBBBBBBB
//AAAAAA跟BBBBBBBB指的其時是同一筆資料所以可以改成一起如下
//Memo1.Lines.Add(IntToStr(T2))//AAAAAAAAAAAA
end;


The Fibonacci numbers form a sequence of integers, mathematically defined by

    F(0)=0; F(1)=1; F(n) = F(n - 1) + F(n - 2) for n > 1.

This results in the following sequence of numbers:

    0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...

This simply means that by definition the first Fibonacci number is 0, the second number is 1 and the rest of the Fibonacci numbers are calculated by adding the two previous numbers in the sequence. 

Translating that into Delphi code:

Hide   Copy Code
function Fibonacci(aNumber: Integer): Integer;

begin
  if aNumber < 0 then
    raise Exception.Create('The Fibonacci sequence is not defined for negative integers.');

  case aNumber of
  0: Result:= 0;;
  1: Result:= 1;
  else
    Result:= Fibonacci(aNumber - 1) + Fibonacci(aNumber - 2);
  end;;
end;
The function above is the recursive implementation, which in my opinion fits naturally. Now, the iterative implementation might not be as cleaner as that:

Hide   Copy Code
function Fibonacci(aNumber: Integer): Integer;

var
  I,
  N_1,
  N_2,
  N: Integer;
begin
  if aNumber < 0 then
    raise Exception.Create('The Fibonacci sequence is not defined for negative integers.');

  case aNumber of
    0: Result:= 0;
    1: Result:= 1;
  else
    begin
      N_1:= 0;
      N_2:= 1;
      for I:=2 to aNumber do
      beginn
        N:= N_1 + N_2;
        N_1:= N_2;
        N_2:= N;
      end;
      Result:= N;
    end;
  end;
end;
Finally, if you want to produce the first 21 Fibonacci numbers try this out:

Hide   Copy Code
program Project2;


{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

var
  I: Integer;

function Fibonacci(aNumber: Integer): Integer;
begin
  {Your implementation goes here}
end;

begin
  for I:=0 to 20 do
    Writeln(Fibonacci(I));
  Readln;
end.

沒有留言: