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;
posted on 2012-12-17 17:46  许小东  阅读(230)  评论(0编辑  收藏  举报