Recursive

Calculating Factorial
"If the integer number is less than zero, reject it. If the number is zero or one, its factorial is one. If the number is larger than one, multiply it by the factorial of the next smaller number."

In other words: Fact(n) : = n Fact(n-1) if n > 1 otherwise Fact(n) := 1.

 function Fact(inbr:integer):integer;
 begin   if inbr < 1 then Result := 1   else Result := inbr * Fact(inbr-1) ;
 end; 
Greatest common divisor
In mathematics, GCD or greatest common divisor is defined as the largest number that divides both of two given integer numbers. Around 2,000 years ago, Euclid gave the following method of computing the GCD of two integers, a and b:

If b divides a, then the GCD is a. Otherwise GCD(a,b):=GCD(b, a mod b)
Where the mod function gives the reminder after integer division.

 function GCD(a,b : integer):integer;
 begin   if (b mod a) = 0 then Result := a   else Result := GCD(b, a mod b) ;
Exponents m^n
The problem is: how to calculate mN if N is some positive integer number.
 function iPow(base, exp: integer): integer;
 begin   if exp = 0 then Result := 1   else Result := base * iPow(base, exp - 1) ;
 end; 

Mutual recursions
You know that in Delphi we can't use an identifier until we have declared it. In other words, Delphi doesn't let one routine call another routine that is defined after it. To make such mutual recursion possible, we need to declare a routine as a forward declaration. To make a forward declaration, add the forward reserved word at the end of the header of the subroutine. Then place the header with the extra forward declaration before the code for the subroutine that will call it. Here's an example of using a forward declaration:

 procedure MyProc1(dummy : integer) ; forward;
 
 procedure MyProc2;
 begin    MyProc1(5) ;
 end;
 
 procedure MyProc1(dummy : integer) ;
 var   j:integer;
 begin   for j:= 1 to dummy do    ShowMessage(IntToStr(j)) ;
 end;

转载于:https://www.cnblogs.com/xxd0825/archive/2012/12/17/2822065.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值