Description
Let's consider equation:
where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.
You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots.
Input
A single line contains integer n (1 ≤ n ≤ 1018) — the equation parameter.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64dspecifier.
Output
Print -1, if the equation doesn't have integer positive roots. Otherwise print such smallest integer x (x > 0), that the equation given in the statement holds.
Sample Input
2
1
110
10
4
-1
Hint
In the first test case x = 1 is the minimum root. As s(1) = 1 and 12 + 1·1 - 2 = 0.
In the second test case x = 10 is the minimum root. As s(10) = 1 + 0 = 1 and 102 + 1·10 - 110 = 0.
In the third test case the equation has no roots.
给一个数学方程式x*x+s(x)-n=0。n,x均为正整数,s(x)为x各个位数相加的和。如果存在x使方程式成立,输出x的最小值。
思路:
n的范围从0到10的18次方,x的范围大致为0到10的9次方,暴力解决肯定会超时,x的最大值为999999999,所以s(x)的最大值为81,可以对s(x)进行逐个比较,把方程式化成x=sqrt(n+s(x)*s(x)/4)-s(x)/2;s(x)从1开始,根据此方程式求出x,又因为s(x)为x各个位数的和,根据x求出s(x),代入原方程看是否成立。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
int s(long long x)
{
int sum=0;
while(x!=0)
{
sum+=x%10;
x=x/10;
}
return sum;
}
int main()
{
long long n;
while(scanf("%lld",&n)!=EOF)
{
int i;
long long x,root=-1;
for(i=0;i<=81;i++)
{
x=sqrt(n+i*i/4)-i/2;
long long sx=s(x);
if(x*x+sx*x-n==0)
{
root=x;
break;
}
}
printf("%lld\n",root);
}
return 0;
}