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, because 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 returns from the bottom up to the top level}//if the recursive invocation of a function appears at the end of the function, it is 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 ("-----program starts, enter the factorial 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-----
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java recursive, tail recursive, non-recursive processing factorial problem