n!=n* (n-1)!
Import Java.io.bufferedreader;import java.io.inputstreamreader;/** * n factorial, i.e. n! (n (n-1) * (n-2) * ... 1). * 0! why = 1, due to 1!=1*0!. So 0!=1 * * @author Stone * @date 2015-1-6 pm 18:48:00 */public class Factorialrecursion {static long fact (long N) {if (n < 0) return 0; else if (n <= 1) return 1;//n = = 1 | | n = = 0return N * fact (n-1); The temporary memory space that is occupied increases with the hierarchy until there is a direct return value. And then back from the bottom all the way up to the top}//assume that a function's recursive invocation is at the end of today's function, called the tail recursive function, static long fact (long n, long Lastvalue) {//last represents the last calculated number to be multiplied. The initial value should be 1if (N < 0) return 0; else if (n = = 0) return 1; else if (n = = 1) return lastvalue;return fact (n-1, n * lastvalue);} Static long Str2long (String num) {return long.valueof (num);} public static void Main (string[] args) throws Exception {System.out.println ("-----The program starts, enter the order multiplier value to be computed. -----"); BufferedReader br = new BufferedReader (new InputStreamReader (system.in)); String line = Br.readline (), while (!line.equals ("Exit")) {Long n = str2long (line); System.out.println (Fact (n)); System.out.println (Fact (n, 1)); System.out.println (Fact2 (n)); line = Br.readline ();} SYSTEM.OUT.PRINTLN ("-----Program exits-----"); Runtime.getruntime (). EXIT (0);} Calculates the factorial of n non-recursive method private static long Fact2 (long N) throws illegalaccessexception {if (n = = 1 | | n = = 0) { return 1; } if (n < 0) {throw new illegalaccessexception ("parameter Error"); } Long sum = 1; Non-recursive method for (long i = n; I >= 2; i--) {sum = sum * i; } return sum; } }
-----The program starts, enter the factorial value you want to calculate,-----111122223666424242451201201208403204032040320exit-----Program Exits-----
Java recursive, tail recursive, non-recursive processing factorial problem