Factorial.java
Factorial.java
—
Python Source,
989 bytes
File contents
import java.io.*;
public class Factorial {
/*@ requires n >= 0;
@ ensures \result == fact(n);
@*/
public static int factorial(int n) {
int result = 1;
while (n > 0) {
result *= n--;
}
return result;
}
/*@ requires n >= 0;
@ ensures (n == 0 ==> \result == 1)
@ && (n > 0 ==> \result == n*fact(n-1));
@*/
public static /*@pure@*/ int fact(int n) {
return n <= 0 ? 1 : n * fact(n-1);
}
public static void main(String[] param) throws IOException {
while (true) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
System.err.print("Compute factorial of: ");
try {
String input = reader.readLine();
if (input.equals("q"))
return;
int value = Integer.parseInt(input);
int result = factorial(value);
System.err.println("The result is: "+result);
} catch (NumberFormatException ex) {
System.err.println("Invalid Number: "+ex);
}
}
}
}
