java 递归计算n!

采用递归和递推计算n!

 

package resursive;

import java.util.Scanner;

public class FactorialN {
	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		System.out.println("请输入一个整数");
		int i=sc.nextInt();
		
		long l=Factorial(i);
//		long l=Factorial2(i);
		
		System.out.println(i+"的阶乘是"+l);
//		System.out.println(Long.MAX_VALUE);
		
	}
	//计算n!,递归
	public static long Factorial(int n){
		if(n==0){
			return 0;
		}
		if (n==1) {
			return 1;
		}
		
		long ret;
		ret=Factorial(n-1)*n;
		return ret;
	}
	//计算n!,递推
	public static long Factorial2(int n){
		long result=1;
		for (int i = 1; i <=n; i++) {
			result*=i;
		}
		return result;
	}
}

 

你可能感兴趣的:(java)