CSE 130 Winter 2004
Principles of Programming Languages

Factorial Function in Various Languages

The mathematical definition of the factorial function on natural numbers is simply factorial(0) = 1 and factorial(n) = n*factorial(n-1) when n>0. The following are programs to compute this function in several different languages; it is interesting to compare these programs and to reflect on the reasons why each languages does what it does in the way that it does.

C++

int factorial(int number) { int temp; if(number <= 1) return 1; temp = number * factorial(number - 1); return temp; }

Java

public class factorial { public static void main(String[] args) { BigInteger n = BigInteger.ONE; for (int i=1; i<=20; i++) { n = n.multiply(BigInteger.valueOf(i)); System.out.println(i + "! = " + n); } } }

Scheme

(define factorial (lambda (n) (if (= n 1) 1 (* n (factorial (- n 1))))))

Scheme (iterative)

(define iter-factorial (lambda (n) (iter-factorial-helper 1 1 n))) (define iter-factorial-helper (lambda (product counter n) (if (> counter n) (product (iter-factorial-helper (* product counter) (+ counter 1) n))))

ML

fun factorial (0) = 1 | factorial (n) = n * factorial(n-1);

Prolog

factorial(0,1). factorial(N,F) :- N>0, N1 is N-1, factorial(N1,F1).
Back to the First class notes page
To the CSE 130 homepage
Maintained by Joseph Goguen