【codeforces】Non-square Equation(数学推导)

一时失言乱红尘 2022-07-15 07:57 322阅读 0赞

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 cin, cout 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

  1. 2

output

  1. 1

input

  1. 110

output

  1. 10

input

  1. 4

output

  1. -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.

本题用二分是不行的,因为y=x+s(x)*x并不是单调递增的。

我们看直接暴力肯定会超时的。所以要看怎么优化,这就需要用到一些数学知识了。看下面这组公式:

Center

我们估算x不会超过10^9,所以s(x)不会超过81;

由上述公式我们就可以对s(x)的值遍历一遍,求出相应的x,再检验此x值是否符合所给公式。从而避免了直接对x遍历超时的情况

  1. #include<cstdio>
  2. #include<iostream>
  3. #include<cstring>
  4. #include<cmath>
  5. #include<algorithm>
  6. #define MAXN 10000000000
  7. using namespace std;
  8. typedef long long LL;
  9. LL solve(LL x){
  10. LL t=0;
  11. while(x){
  12. t=t+x%10;
  13. x=x/10;
  14. }
  15. return t;
  16. }
  17. int main(){
  18. LL n;
  19. while(scanf("%lld",&n)!=EOF){
  20. LL ans=MAXN;
  21. for(int i=1;i<=81;i++){
  22. LL x=sqrt(i*i/4+n)-i/2;
  23. LL s=solve(x);
  24. if(x*x+x*s-n==0){
  25. ans=min(ans,x);
  26. break;
  27. }
  28. }
  29. if(ans!=MAXN)
  30. printf("%lld\n",ans);
  31. else
  32. printf("-1\n");
  33. }
  34. return 0;
  35. }

发表评论

表情:
评论列表 (有 0 条评论,322人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Equation

    \\(Equation\\) ![m6aGge.png][] 这道题目把式子两面移一下项,变为 \\\[a\_1\x\_1+a\_3\x\_3+a\_5\x\_5=

    相关 反向传播的数学推导

    前一篇手写识别的博文《[深度学习数学基础—反向传播][Link 1]》中已经简单分析和推导过反向传播的原理,但是基于特定的场景给出的推导过程,现在我们再来系统的加深下神经网络反

    相关 数学推导】数字变换

    题目描述 Alice 给了 Bob 一个数 k,求有多少个数 x,满足:从 x 的某个数位(不能是最后一位)后加一个乘号,运算得到一个数 y,使得 x−y=k。 比如: