B. Non-square Equation
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
Let's consider equation:
x2 + s(x)·x - n = 0,
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.
Examples
input
Copy
2
output
Copy
1
input
Copy
110
output
Copy
10
input
Copy
4
output
Copy
-1
Note
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=(-b+√ ̄b*b-4ac) /2a(正根)可大概得出x最大值数量级为10的9次方
即最大为999999999,sx最大为81,故可以枚举sx来完成求解,但实际上这是有瑕疵的,
但这种思想还是需要学习学习的*/
#include <iostream>
#include <cmath>
using namespace std;
long long init(long long x) //用于求sx
{
long long sum=0;
while(x)
{
sum+=x%10;
x/=10;
}
return sum;
}
int main()
{
long long n,ans,x,sx;
int i,j,k;
while(cin>>n)
{
ans=-1;
for(i=1;i<=81;i++) //枚举sx
{
x=sqrt(i*i/4+n)-i/2; //根据公式求x,其实可以明显看出来这样是不对的,i*i/4算出来的数字极有可能不符合,他算出来的肯定是整数
sx=init(x); //求sx,因为x算出来可能跟枚举的sx不对应,所以要再求一遍,有碰运气的嫌疑,也就是这道题的不好之处
if(x*x+sx*x==n)
{
ans=x;
}
}
cout<<ans<<endl;
}
}