Calculate the factorial of a number

From CodeCodex

Revision as of 20:47, 2 August 2006 by Jdh30 (Talk | contribs)

These while loops will calculate the factorial of a number: [edit]

Visual Basic / QBasic

Dim counter as Integer : counter = 5
Dim factorial as Long : factorial = 1
While (counter > 0)
  factorial = factorial * counter     'Multiply
  counter = counter - 1               'Decrement
Wend
Print factorial                       'Prints out the result.

REALbasic

Dim counter as Integer = 5
Dim factorial as Integer = 1
While counter > 0
  factorial = factorial * counter     //Multiply
  counter = counter - 1               //Decrement
Wend
MsgBox Str( factorial )               // Prints out the result.

C or C++

unsigned int counter = 5;
unsigned long factorial = 1;
while (counter > 0)
{
  factorial *= counter--; /*Multiply, then decrement.*/
} 
printf("%i", factorial);

Perl

my $counter   = 5;
my $factorial = 1;
while ( $counter > 0 ) 
{
    $factorial *= $counter--; # Multiply, then decrement
}
print $factorial;

Very similar to C and C++, but the while loop could also have been written on one line:

$factorial *= $counter-- while ( $counter > 0 );

Tcl (Tool command language)

set counter 5
set factorial 1
while {$counter > 0} {
  set factorial [expr $factorial * $counter] 
  incr counter -1 
}
puts $factorial


Java, Csharp

The code for the loop is the same for Java and Csharp:

int counter = 5;
long factorial = 1;
while (counter > 0)
   factorial *= counter--; // Multiply, then decrement.

For Java the result is printed as follows:

System.out.println(factorial);

The equivalent in C# is:

System.Console.WriteLine(factorial);

OCaml

# let rec f n = if n=0 then 1 else n*f(n-1);;
val f : int -> int = <fun>

For example:

# f 5;;
- : int = 120

Pascal

program Factorial
var
  Counter, Factorial: integer;
begin
  Counter := 5;
  Factorial := 1;
  while Counter > 0 do begin
    Factorial := Factorial * Counter;
    Counter := Counter - 1;
  end;
  Write(Factorial);
end.

Python

counter = 5
factorial = 1
while counter>0:
      factorial *= counter
      counter -= 1
print factorial

Source