B. Non-square Equation

来源:互联网 发布:java 1.7 32位 linux 编辑:程序博客网 时间:2024/05/22 16:38

time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Let's consider equation:

x2 + s(xx - 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 cincout streams or the%I64d specifier.

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 test(s)
input
2
output
1
input
110
output
10
input
4
output
-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.


解题说明:x2 + s(xx - n = 0,  给出n的值,求x的值,这里s(x)表示x各位数字的和。这里我能够得到x<10^9那么s(x)< 10*9 = 90 我们只要枚举s(x) 然后得到一个普通的一元二次方程,a*x^2 + b*x + c = 0然后根据公式,x = (-b +or - sqrt(b^2 -4*a*c )/2这里我们求的都是整数解,所以在计算的时候我们要保证得到的解是整数。

#include<iostream>#include<cstdio>#include<cmath>#include<algorithm>using namespace std;int main(){  long long x,st,n,temp;  int i,sum=0;  double d;  scanf("%I64d",&n);  for(i=1;i<=162;i++)  {   d = sqrt((double)(i*i + 4*n));   st = (long long)d;   if((double)st==d)   {   x = (long long)d - (long long)i;   if(x%2==0){temp = x/2; sum = 0; while(temp) {  sum+=temp%10;  temp/=10; }    if(sum==i)    { break; }   }   }  }   if(i>162)   {   printf("-1\n");   }   else   {   printf("%I64d\n",x/2);   }   return 0; }