Java_CH5_HW1
試設計一個程式,列印出從整數1到20,但不含兩
位數偶數的階乘。
(參閱 Example 5.16. recusion .java ,下一張投影 片課本5.10習題。)
輸入 1 : 列印不含2位數偶數的1-20階乘。
輸入 2 : 列印不含2位數奇數的1-20階乘。
輸入 3 : 列印 “ 無法判斷”。
(參閱 Example 5.16. recusion .java ,下一張投影 片課本5.10習題。)
輸入 1 : 列印不含2位數偶數的1-20階乘。
輸入 2 : 列印不含2位數奇數的1-20階乘。
輸入 3 : 列印 “ 無法判斷”。
import java.util.*;
public class Java_CH5_HW1
{
public static void main(String[] args)
{
// TODO 自動產生的方法 Stub
Scanner scan = new Scanner(System.in);
System.out.print("請輸入:");
int input = scan.nextInt();
Factorial f = new Factorial();
if (input == 1)
for (int i = 1; i <= 20; i++)
System.out.println("Factorial of " + i + " is " + f.fact(i, 0) + ".");
else if (input == 2)
for (int i = 1; i <= 20; i++)
System.out.println("Factorial of " + i + " is " + f.fact(i, 1) + ".");
else
System.out.println("無法判斷");
}
}
class Factorial
{
long fact(int n, int num)
{
long temp = 1, result;
if (n == 1)
return 1;
else if (n % 2 != num && n > 10)
temp *= n;
result = fact(n - 1, num) * n;
return result / temp;
}
}
留言
張貼留言