/*思路:由目標式子可見分為兩個部分。一個為每一項求階乘數,另外一個為求和。所以寫兩個方法就可以解決。*/
public class PracticeDemo {
//遞歸方法求每一位的階乘,返回為該數的階乘。從1開始
public static long Recursion(int a)
{
long value = 0;
if(1 == a )
{
value = 1;
}
else if(1 < a)
{
value = a * Recursion(a-1);
}
return value;
}
//階乘求和從0到b的階乘之和
public static long Summation(int b)
{
long Sum = 0;
if(0 > b)
{
return -1;
}
else
{
while(0 < b)
{
System.out.print(b+"!+");
Sum += Recursion(b);
b--;
}
System.out.print("0!=");
return Sum+1; //加上0的階乘
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("請輸入你要求的目標數:");
int a = input.nextInt();
PracticeDemo trf = new PracticeDemo();
System.out.println(trf.Summation(a));
}
}
//改進方法
/*此方法利用一個for循環。時間復雜度為O(n)。在循環里面兩個變量,一個用于每次i++成為下一個數的階乘;另一個為求和變量*/
Scanner input = new Scanner(System.in);
System.out.println("請輸入你要求的目標數:");
int a = input.nextInt();
int temp = 1;
int sum = 0;
for(int i = 1;i <= a;i++)
{
temp *= i; //用于計算每一個階乘
sum += temp ; //階乘累加
System.out.print(i+"!+");
}
System.out.println("0="+sum);