Java_CH5_HW1

試設計一個程式,列印出從整數1到20,但不含兩 位數偶數的階乘。
(參閱 Example 5.16. recusion .java ,下一張投影 片課本5.10習題。)
輸入 1 : 列印不含2位數偶數的1-20階乘。
輸入 2 : 列印不含2位數奇數的1-20階乘。
輸入 3 : 列印 “ 無法判斷”。



  1. import java.util.*;
  2.  
  3. public class Java_CH5_HW1
  4. {
  5.  
  6. public static void main(String[] args)
  7. {
  8. // TODO 自動產生的方法 Stub
  9. Scanner scan = new Scanner(System.in);
  10. System.out.print("請輸入:");
  11. int input = scan.nextInt();
  12. Factorial f = new Factorial();
  13. if (input == 1)
  14. for (int i = 1; i <= 20; i++)
  15. System.out.println("Factorial of " + i + " is " + f.fact(i, 0) + ".");
  16. else if (input == 2)
  17. for (int i = 1; i <= 20; i++)
  18. System.out.println("Factorial of " + i + " is " + f.fact(i, 1) + ".");
  19. else
  20. System.out.println("無法判斷");
  21. }
  22.  
  23. }
  24.  
  25. class Factorial
  26. {
  27. long fact(int n, int num)
  28. {
  29. long temp = 1, result;
  30. if (n == 1)
  31. return 1;
  32. else if (n % 2 != num && n > 10)
  33. temp *= n;
  34. result = fact(n - 1, num) * n;
  35. return result / temp;
  36. }
  37. }

留言

這個網誌中的熱門文章

C# 井字遊戲