题目链接:FZU 2125 简单的等式
x小于10^9,那S的值不会太大,所以可以枚举S,然后再回带检查是否成立,题目要求x是正整数,所以要回带方程中,这样如果通过求根公式算出来是浮点数,然后截断成整数,回带后方程是不会成立的,不能单单判断S(x1, m)是否等于i,这样很有可能是相等的。
注意这么写才对const long long INF = ((long long)1 << 63),不能这么写const long long INF = (1 << 63),很容易错。
FZU居然不能用lld读==。
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const long long INF = ((long long)1 << 63);
long long S(long long x, long long m)
{
long long ans = 0;
while(x)
{
ans += (x % m);
x /= m;
}
return ans;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
long long n, m, x1, x = INF;
cin >> n >> m;
for(int i = 0; i <= 200; i++)
{
x1 = (-i + sqrt(i * i + 4 * n)) / 2;
if(x1 * x1 + x1 * S(x1, m) == n)
x = min(x, x1);
}
if(x != INF)
cout << x << endl;
else
puts("-1");
}
return 0;
}