1760: 康康的阶乘
时间限制: 1 Sec 内存限制: 128 MB
提交: 223 解决: 44
您该题的状态:已完成
[提交][状态][讨论版]
题目描述
In class, kangkang learned to use the computer to solve N factorial, and then came home to show off to Jane. In order not to let kangkang be too complacent, Jane gave kangkang a question "since you're going to ask for N factorial, you'll help me figure out 1! + 2! -3! + 4! -5! +... N!" It is. Can you help him?
输入
The first line enters an integer T (0 < = 20), which represents T group test data.
After that, it has T rows, and each row enters a positive integer N (0 < N < = 20).
输出
Each group of test data accounts for one line, output 1! + 2! - 3! +... .. N! The value of the.
样例输入
2
4
样例输出
3
21
#include<stdio.h>
int main() {
long long a[30];//用long long。
a[0]=1;
for(int i=1; i<=20; i++)
a[i]=a[i-1]*i;
预处理,防止超时。
int t,n;
long long ans;
scanf("%d",&t);
while(t--) {
ans=1;
scanf("%d",&n);
if(n==1)
printf("1\n");
else {
for(int i=2; i<=n; i++) {
if(i%2==0)
ans+=a[i];
else if(i%2==1)
ans-=a[i];
}
printf("%lld\n",ans);
}
}
return 0;
}