1. Introduction
There are a lot of ways to achieve factorial, here are three methods, namely recursion, tail recursion, circulation and BigDecimal.
2. Code
public class Test {public static void main (string[] args) {//TODO auto-generated method Stubalogrithm A = new ALOGRITHM1 ( ); A.fact (5); A.print (A.FACTN (6)); A.print (A.factfor (7));}} Class alogrithm{void fact (int n) {fact_inter (n,1);} int fact_inter (int n, int product) {if (n = = 1 | | n = = 0) {System.out.println ("Step n=" + N + "value:" +product); return 1*prod UCT;} Else{system.out.println ("Step n=" + N + "value:" +product); return Fact_inter ((n-1), n*product);}} int factn (int n) {if (n = = 1 | | n==0) {return 1;} Else{return n*factn (n-1);}} int factfor (int n) {int sum = 1;if (n = = 0) {return 1;} for (int i = 1; I <= n; i++) {sum*=i;} return sum;} void print (int x) {System.out.println ("x=" + x);}}
3. Output
Step n=5 value:1step n=4 value:5step n=3 value:20step n=2 value:60step n=1 value:120x=720x=5040
4. Description
Output N of type int can only be supported to 12, and in 12-33 the value will get the wrong output value may be positive negative, 34 and above output 0.
A long type of output n can only be supported to 20, and in 20-65 the value will get the wrong output value may be positive negative, 36 and above output 0.
5. The BigDecimal is coming.
Modify the following section of the code below:
public class Test {public static void main (string[] args) {//TODO auto-generated method Stubalogrithm A = new ALOGRITHM1 ( ); A.fact (5); A.print (A.FACTN (6)); A.print (A.factfor (7));
A.print (A.factbig (100));
A.print (A.factbig (1000));
}}
BigDecimal recursive method, the other two ways to replace int to BigDecimal processing is also equivalent to public BigDecimal factbig (int n) {if (n = = 1 | | n==0) {return Bigdecimal.valueof (1);} Else{return bigdecimal.valueof (n). Multiply (Factbig (n-1));}} Modify output void print (Object x) {System.out.println ("x=" + x.tostring ());}
So the value of the child n can be very large, not limited by the length of int and long.
[Java] function to find factorial n! (factorial) (four methods)