1. 程式人生 > >Java 遞歸、尾遞歸、非遞歸 處理階乘問題

Java 遞歸、尾遞歸、非遞歸 處理階乘問題

mon 問題 content while pos 程序 article div get

n!=n*(n-1)!

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * n的階乘,即n! (n*(n-1)*(n-2)*...1)。

* 0!為什麽=1,由於1!=1*0!。所以0!=1 * * @author stone * @date 2015-1-6 下午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 == 0 return n * fact(n - 1); //占用的暫時內存空間隨著層級越來越大,直至有直接返回值時。再從底層一路向上返回到頂層 } //假設一個函數的遞歸形式的調用出如今函數的末尾,則稱為 尾遞歸函數 static long fact(long n, long lastValue) {//last表示要被相乘的上次求出的數。初始值應為1 if (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("-----程序開始,請輸入要計算的階乘數值。-----"); 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("-----程序退出-----"); Runtime.getRuntime().exit(0); } //計算n的階乘 非遞歸法 private static long fact2(long n) throws IllegalAccessException { if (n == 1 || n == 0) { return 1; } if (n < 0) { throw new IllegalAccessException("參數錯誤"); } long sum = 1; // 非遞歸法 for (long i = n; i >= 2; i--) { sum = sum * i; } return sum; } }


-----程序開始,請輸入要計算的階乘數值,-----
1
1
1
1
2
2
2
2
3
6
6
6
4
24
24
24
5
120
120
120
8
40320
40320
40320
exit
-----程序退出-----


Java 遞歸、尾遞歸、非遞歸 處理階乘問題