12以内20以内100以内的阶乘方法

<br style="font-size: 24px; font-weight: bold;" /><span style="font-size: 24px; "><strong>12以内、20以内、100以内、1000以内的阶乘方法</strong></span>
package com.firstACMTest;

import java.math.BigDecimal;
import java.math.BigInteger;

public class 阶乘总结 {
	/*
	 * 
	 * 动态规划中的阶乘
	 */

	public static int J[] = new int[1000];

	public static int jiechengDT(int n) {
		int t = 0;
		if (J[n] != 0)
			return J[n];
		if (n <= 1)
			t = 1;
		if (n > 1)
			t = n * jiechengDT(n - 1);
		return J[n] = t;

	}

	/*
	 * 20以内的阶乘普通方法
	 */

	public static Long jiecheng(int n) {
		if (n < 1)
			return 1L;
		return n * jiecheng(n - 1);
	}

	/*
	 * 12以内的阶乘普通方法
	 */
	public static int jiecheng1(int n) {
		if (n < 1)
			return 1;
		return n * jiecheng1(n - 1);

	}

	/*
	 * 大于20的阶乘用BigDecimal方法参数是BigDecimal类型
	 */
	public static BigDecimal factorial(BigDecimal n) {
		BigDecimal bd1 = new BigDecimal(1);// BigDecimal类型的1
		BigDecimal bd2 = new BigDecimal(2);// BigDecimal类型的2
		BigDecimal result = bd1;// 结果集,初值取1
		while (n.compareTo(bd1) > 0) {// 参数大于1,进入循环
			result = result.multiply(n.multiply(n.subtract(bd1)));
			n = n.subtract(bd2);// n-2后继续
		}
		return result;
	}

	/*
	 * 大于20的阶乘用BigInteger方法参数是int类型
	 */
	public static BigInteger bigIntegerFactorial(int num) {
		BigInteger result = BigInteger.valueOf(1);// 定义大整数,初始值为1
		for (int i = 1; i <= num; i++) {
			BigInteger n = BigInteger.valueOf(i);
			result = result.multiply(n);
		}
		return result;
	}

	/*
	 * 大于20的阶乘用BigInteger方法参数是String类型 此String类型必须可以转换成整数类型,或者是题目可以给出1-N的阶乘
	 * String值转化成BigInteger为new BigInteger(String.valueOf(i))
	 */
	public static BigInteger bigIntegerFactorial(String num) {
		BigInteger result = new BigInteger("1");
		int N = Integer.parseInt(num);
		for (int i = 1; i <= N; i++) {
			result = result.multiply(new BigInteger(String.valueOf(i)));
		}
		return result;
	}

	/*
	 * 大于20的阶乘用BigInteger方法参数是BigInteger类型 BigInteger.ONE表示大整数
	 */
	public static BigInteger bigIntegerFactorial(BigInteger num) {
		BigInteger result;
		if (num.equals(BigInteger.ONE))
			return BigInteger.ONE;
		return num.multiply(bigIntegerFactorial(num.subtract(BigInteger.ONE)));
	}

	public static void main(String[] args) {

	}

}



你可能感兴趣的:(java,算法)