Calculate the factorial of a number

From CodeCodex

Revision as of 16:46, 10 January 2007 by 71.120.229.114 (Talk)

These while loops will calculate the Factorial of a number:

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
proc factorial n {
  if {$n <= 0} {
    return 1
  } else {
    return [expr {$n * [factorial [expr {$n - 1}]]}]
  }
}

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);

Rather than using a loop, use a recursive method:

    /**
     * A recursive factorial calculation method
     *
     * @param n the number to be factored
     * @return the factorial of n
     */
    public static int factorial(int n) {
        return ((n == 0) ? 1 : n * factorial(n - 1));
    }

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

Scheme

(define (fac n)
 (if (= n 0)
     1
     (* n (fac (- n 1)))))
;give fac a value of 5
(fac 5)

Source