1 second
256 megabytes
standard input
standard output
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.
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%I64d specifier.
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.
2
1
110
10
4
-1
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(x)·x - 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; }