? 用三种方法来实现n!实现使用BigDecimal类,因为用int最多正确算到12!,用long最多正确算到20!.废话不多说,直接上代码:
?
? 第一种方法:
?//第一种方法:
package Factorial; import java.math.BigDecimal; import java.util.Scanner; public class Factorial1 { public static BigDecimal factorial(int n){ BigDecimal result = new BigDecimal(1); BigDecimal a; for(int i = 2; i <= n; i++){ a = new BigDecimal(i); result = result.multiply(a); } return result; } public static void main(String[] arguments){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); System.out.println(a + "!=" + factorial(a)); } }
?
? 第二种方法:
?
?
//第二种方法 package Factorial; import java.math.BigDecimal; import java.util.Scanner; public class Factorial3 { public static BigDecimal factorial(BigDecimal n){ BigDecimal bd1 = new BigDecimal(1); BigDecimal bd2 = new BigDecimal(2); BigDecimal result = bd1; while(n.compareTo(bd1) > 0){ result = result.multiply(n.multiply(n.subtract(bd1))); n = n.subtract(bd2); } return result; } public static void main(String[] arguments){ Scanner sc = new Scanner(System.in); BigDecimal n = sc.nextBigDecimal(); System.out.print(n + "!=" + factorial(n)); } }?
?第三种方法,用递归实现:
?
?
package Factorial; import java.util.Scanner; import java.math.BigDecimal; public class Factorial2 { public static BigDecimal factorial(BigDecimal n){ BigDecimal bd1 = new BigDecimal(1); if(n.equals(new BigDecimal(1))){ return bd1; } else return n.multiply(factorial(n.subtract(bd1))); } public static void main(String[] arguments){ Scanner sc = new Scanner(System.in); BigDecimal a = sc.nextBigDecimal(); BigDecimal result = factorial(a); System.out.println(a + "!=" +result); } }?
?