原题链接:
题目描述:
A number is called powerful if it is a power of two or a factorial. In other words, the number mm is powerful if there exists a non-negative integer dd such that m=2dm=2d or m=d!m=d!, where d!=1⋅2⋅…⋅dd!=1⋅2⋅…⋅d (in particular, 0!=10!=1). For example 11, 44, and 66 are powerful numbers, because 1=1!1=1!, 4=224=22, and 6=3!6=3! but 77, 1010, or 1818 are not.
You are given a positive integer nn. Find the minimum number kk such that nn can be represented as the sum of kk distinct powerful numbers, or say that there is no such kk.
Input
Each test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100). Description of the test cases follows.
A test case consists of only one line, containing one integer nn (1≤n≤10121≤n≤1012).
Output
For each test case print the answer on a separate line.
If nn can not be represented as the sum of distinct powerful numbers, print −1−1.
Otherwise, print a single positive integer — the minimum possible value of kk.
题目大意:
题意:给出一个数 n n可以有一些数相加组成
这些数的要求是:
1.是某个数的阶乘
2.是2的某整数幂
问组成的数个数最少是多少呢?
解题思路:
分析:n是有范围的 n<10^12 且 小于 10^12 的阶乘数只有15个 可以预处理出
其实根据题意 n= Σ(xi!) + Σ(2yi)) 那么我们可以枚举出 2^15 种阶乘数的选取,然后我们很容易计算出后面部分是需要多少个2幂次数组成
__builtin_popcountll(i) 函数可以直接计算一个数二进制下有多少个1
代码(CPP):
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
typedef unsigned long long ull;
const int maxn = 1e3 + 10;
const int INF = 0x3fffffff;
int n, a[maxn];
void init()
{
a[1] = 1;
for (int i = 2; i <= 15; i++)
a[i] = a[i - 1] * i;
}
void solve()
{
cin >> n;
int ans = __builtin_popcountll(n);
for (int i = 0; i < (1 << 16); i++)
{
int sum = 0;
for (int j = 0; j < 16; j++)
{
if (i & (1 << j))
sum += a[j];
}
if (sum <= n)
ans = min(ans, (int)__builtin_popcountll(i) + __builtin_popcountll(n - sum));
}
cout << ans << endl;
}
signed main()
{
freopen("in.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed;
cout.precision(18);
int t;
cin >> t;
init();
while (t--)
{
solve();
}
return 0;
}