Ignora collegamentiHome / Blog

Blog


How to calculate the factorial of an integer with Java

This simple example written in Java, shows how to calculate the factorial of an integer.
To calculate the factorial of a number n, start the program with java-cp. Factorial n; for example:

java-cp. Factorial 9

calculates the factorial of 9

public class Factorial {
	public static void main(String [] args) {
		int n = 0;
		if(args.length>0) {	
			try {
				n = Integer.parseInt(args[0]);
			}
			catch(NumberFormatException nfe) {
				System.out.println("Invalid input value!");
				System.exit(1);
			}
		}
		if (n < 0) {
		System.out.println("Invalid input value!");
		} 
		else {
		long fact = 1;
		for (int i = 2; i <= Math.abs(n); i++){
		fact = fact * i;
		}
		System.out.println("Factorial of " + Math.abs(n) + " = " + fact);
		}
	}
}

 
For example:

java -cp . Factorial
Factorial of 0 = 1
 
java -cp . Factorial 13
Factorial of 13 = 6227020800
 
java - cp . Factorial four
Invalid input value!
 



Category: Java