Problem Description
现在有一个等式如下:x^2+s(x,m)x-n=0。其中s(x,m)表示把x写成m进制时,每个位数相加的和。现在,在给定n,m的情况下,求出满足等式的最小的正整数x。如果不存在,请输出-1。
Input
有T组测试数据。以下有T(T<=100)行,每行代表一组测试数据。每个测试数据有n(1<=n<=10^18),m(2<=m<=16)。
Output
输出T行,有1个数字,满足等式的最小的正整数x。如果不存在,请输出-1。
Sample Input
44 10110 1015 2432 13
Sample Output
-110318
我们可以知道,x绝对是小于等于根号n的
那么只要枚举就可以了
但是一般的枚举是要超时的
但是我们可以发现
s(x,m)必然有一个范围,可以作为跳出条件
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>
using namespace std;
int main()
{
__int64 t,n,m,ans;
scanf("%I64d",&t);
while(t--)
{
scanf("%I64d%I64d",&n,&m);
__int64 x = sqrt(n*1.0);
ans = -1;
while(x)
{
if(n%x==0)
{
__int64 sum = 0,tem = x;
while(tem)
{
sum+=tem%m;
tem/=m;
}
if(sum == n/x-x)
{
ans = x;
}
}
if(n/x-x>90)
break;
x--;
}
printf("%I64d\n",ans);
}
return 0;
}