Javaでの階乗を求めるアルゴリズム


Javaでの階乗を求めるアルゴリズム
1.一般的なアルゴリズム:
public class Factorial {
	public static int factorial(int n) {
		if (n < 0 || n > 16) {
			System.err.println("n must be great than 0 and less than 17");
			return -1;
		} else if (n == 0) {
			return 1;
		} else {
			int result = 1;
			for (int i = 1; i <= n; i++) {
				result *= i;
			}
			return result;
		}
	}

	public static void main(String args[]) {
		System.out.println("result = " + factorial(5));
	}
} 

   実行結果:result=120
 
2.再帰アルゴリズム:
public class Factorial {
	public static int recursion(int n) {
		if (n < 0 || n > 16) {
			System.err.println("n must be great than 0 and less than 17");
			return -1;
		} else if (n == 0) {
			return 1;
		} else {
			return n * recursion(n - 1);
		}
	}

	public static void main(String[] args) {
		System.out.println("result = " + recursion(16));
	}
}

 実行結果:result=2004189184
 
3.BigIntegerの使用
import java.math.BigInteger;

public class Factorial {
	public static BigInteger bigInteger(int n) {
		BigInteger result = new BigInteger("1");
		if (n < 0) {
			System.err.println("n must be great than 0");
			return new BigInteger("-1");
		} else if (n == 0) {
			return new BigInteger("1");
		} else {
			for (int i = 1; i <= n; i++) {
				BigInteger num = new BigInteger(String.valueOf(i));
				result = result.multiply(num);
			}
			return result;
		}
	}

	public static void main(String[] args) {
		System.out.println("result = " + bigInteger(100));
	}
}

 実行結果:result=933262154433944152616923885626670049015966843816214688592963895
217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000