Codeforces 233B:Non-square Equation(数学+思维)

来源:互联网 发布:java 表单提交 编辑:程序博客网 时间:2024/05/16 03:47
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(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 %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
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.

题目大意:给你一个n,n=x2 + s(xx ,让你求一个最小的x满足这个式子,如果没有的话输出-1.其中s(x)为x的各位数之和。

解题思路:很容易往二分方向想,但是这不是个单调递增或递减函数,所以不能用二分。

换个思维,题目上说n介于1~10^18那么大,那么大概让n=x^2,那么x大概在1~1^9那么大,那么s(x)大概9个9那么大,

也就是s(x)最多是81,那么枚举s(x),相当于x2 + s(xx -n=0,a=1,b=s(x)(a、b都知道了,(b是枚举出来的)),那么

求根x,用求根公式求出x,然后反代入原式,看是否符合即可。

代码如下:

#include <cstdio>#include <cmath>#define LL __int64LL getsum(LL x)//求一个数字的各位数之和 {LL sum=0;while(x){sum=sum+x%10;x=x/10;}return sum;}int main(){LL n;scanf("%I64d",&n);LL ans=-1;//初始化结果为-1,以便找不到合适结果时直接输出 for(LL i=1;i<=90;i++)//枚举s(x) {LL tmp=i*i+4*n;LL deta=sqrt(tmp);//求deta(拼音)。。。 if(deta*deta==tmp)//看是否为整数 {deta=deta-i;if(deta%2==0&&getsum(deta/2)==i)//(求根公式最后除二,看是否为整数),再判断所求出的根的各位数之和是否为s(x) {ans=(deta/2);break;//最小,一旦找到就break }}}printf("%I64d\n",ans);return 0;} 


0 0
原创粉丝点击