- import java.util.Scanner;
- public class JPA04 {
- static Scanner keyboard = new Scanner(System.in);
- public static void main(String args[]) {
- while (true) {
- System.out.print("Input n (0 <= n <= 16): ");
- int n = keyboard.nextInt();
- if (n == 999)
- break;
- System.out.printf("%d 的階乘(尾端遞迴) = %d\n", n, Tail(n, 1));
- System.out.printf("%d 的階乘(迴圈) = %d\n", n, Loop(n, 1));
- }
- }
- public static int Tail(int n, int m) {
- if (n == 1)
- return m;
- else
- return Tail(n - 1, m * n);
- }
- public static int Loop(int n, int m) {
- while (n > 1) {
- m *= n;
- n--;
- }
- return m;
- }
- }
複製代碼 |