欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java中求阶乘的算法 博客分类: Java 算法Java 

程序员文章站 2024-03-22 10:20:17
...

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 = 93326215443944152681699238856266700490715968264381621468592963895

217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

 

  

 

 

 

相关标签: 算法 Java