Description
给你一个非负数整数N,判断N是不是一些数(这些数不允许重复使用,且为正数)的阶乘之和,如9=1!+2!+3!,如果是,则输出Yes,否则输出No
Input
第一行有一个整数M(0 < M < 100)表示有M组测试数据;
每组测试数据有一个正整数N(0 < N <= 100000);
Output
如果符合条件,输出Yes,否则输出No;
Sample Input
3
24
29
31
Sample Output
Yes
No
Yes
tips
这道题可以老老实实用递归或者循环来做,虽然时间可能会比较久。另外也可以直接算出所有符合情况的结果,直接投机取巧,时间复杂自然最小。
Source
1.递归版
#include<iostream>
#include<cstdio>
#include<vector>
#include<iterator>
using namespace std;
int jc(int i) {
if (i <= 2)
return i;
return jc(i - 1) * i;
}
void judge(int num) {
for (int i = 8; i > 0; i--) {
if (jc(i) <= num)
num = num - jc(i);
}
if (num == 0)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
int main() {
int n,tmp;
scanf("%d", &n);
vector<int>num;
for (int i = 0; i < n; i++) {
scanf("%d", &tmp);
num.push_back(tmp);
}
for (int i = 0; i < n; i++) {
judge(num[i]);
}
return 0;
}
2.偷鸡版
#include<iostream>
#include<cstdio>
#include<vector>
#include<iterator>
using namespace std;
void judge(int num) {
int a[9] = { 1,2,6,24,120,720,5040,40320,362880 };
for (int i = 8; i >= 0; i--) {
if (a[i] <= num)
num = num - a[i];
}
if (num == 0)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
int main() {
int n,tmp;
scanf("%d", &n);
vector<int>num;
for (int i = 0; i < n; i++) {
scanf("%d", &tmp);
num.push_back(tmp);
}
for (int i = 0; i < n; i++) {
judge(num[i]);
}
return 0;
}