递归练习

递归练习-兔子繁殖 

AYYZOJ p1411

 1 program rabit;
 2   var  n,p:longint;
 3 function fib(m:longint):longint;
 4   begin
 5    if m=0 then fib:=0
 6           else if m=1 then fib:=1
 7                    else fib:=fib(m-1)+fib(m-2);
 8   end;
 9 begin
10  readln(n);
11    p:=fib(n);
12    writeln(p)
13 end.
递归
 1 program p1411;
 2 var
 3  n,i,x,y,z:longint;
 4 begin
 5  readln(n);
 6   x:=0;y:=1;
 7   if n=1 then writeln(1) else begin
 8   for i:=2 to n do
 9    begin
10     z:=x+y;
11     x:=y; y:=z;
12    end;
13  writeln(z); end;
14 end.
非递归

递归练习-杨辉三角

AYYZOJ p1412

 1 var
 2   n:integer;
 3   a:array[1..20,1..20] of longint;
 4 procedure print(i,j:integer);
 5   begin
 6     if j=1 then begin a[i,1]:=1;write(1);exit;end;
 7     print(i,j-1);
 8     a[i,j]:=a[i-1,j]+a[i-1,j-1];
 9     write(' ',a[i,j]);
10   end;
11 procedure yh(n:integer);
12   var i:integer;
13   begin
14     if n=1 then begin a[1,1]:=1; writeln(a[1,1]);exit;end;
15     yh(n-1);
16     print(n,n-1);
17     a[n,n]:=1;
18     writeln(' ',1);
19   end;
20 
21 begin
22   readln(n);
23   yh(n);
24 end.
递归
 1 program p1412;
 2 type arr=array[1..20,1..20] of longint;
 3 var
 4  n:integer;
 5  f:arr;
 6 procedure YHSJ(x:integer);
 7 var
 8  i,j:integer;
 9 begin
10  for i:=1 to x do
11  begin
12   for j:=1 to i do
13    begin
14     if (j=1) or (j=i) then f[i,j]:=1
15     else f[i,j]:=f[i-1,j]+f[i-1,j-1];
16     write(f[i,j],' ');
17    end;
18   writeln;
19  end;
20 end;
21 begin
22  readln(n);
23  YHSJ(n);
24 end.
非递归

递归练习-进制转换

AYYZOJ p1414

 1 var
 2  m:integer;
 3 procedure tran(n:integer);
 4 var k:integer;
 5 begin
 6  k:=n mod 8;
 7  n:=n div 8;
 8  if n<>0 then tran(n);
 9  write(k);
10 end;
11 begin
12  read(m);
13  tran(m);
14 end.
递归
 1 program p1414;
 2 var
 3  n,h:integer;
 4 procedure turndata(n,a:integer);
 5 var
 6  x:array[1..16] of integer;
 7  i,j,k,h:integer;
 8 begin
 9  if n<0 then writeln('-');
10  j:=abs(n);
11  k:=0;
12  repeat
13   inc(k);
14   i:=j mod a;
15   j:=j div a;
16   x[k]:=i;
17  until j=0;
18  for h:=k downto 1 do
19   if x[h]<10 then write(x[h])
20    //else write(chr(55+x[h]));
21 end;
22 begin
23  readln(n);
24  turndata(n,8);
25 end.
非递归
posted @ 2016-02-02 12:59  ZJQCation  阅读(320)  评论(0编辑  收藏  举报