北邮机试 | bupt oj | 130. 非平方等式

版权声明:本人小白,有错误之处恳请指出,感激不尽;欢迎转载 https://blog.csdn.net/stone_fall/article/details/88647483

时间限制 1000 ms 内存限制 262144 KB

题目描述

考虑等式:

x2 + s(xx - n = 0, 

其中x,n是正整数,s(x)是个函数,其值等于x在十进制下所有数字的和。

现给出整数n的大小,请你求出最小的满足条件的正整数x。

输入格式

输入仅包含一个整数n (1 ≤ n ≤ 1018) .

输出格式

如果不存在这样的x,请输出-1;否则请输出满足条件的最小的整数x (x > 0)

输入样例

2

输出样例

1

AC代码

分析:n最大10^18,sqrt(n)=10^9,n=x^2+x*s(x)>x^2,且n=x(x+s(x))<(x+s(x))(x+s(x))的。由此可知:sqrt(n)-9*9<x<sqrt(n)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll s(ll x)
{
    ll res=0;
    while(x)
    {
       res+=x%10;
       x=x/10;
    }
    return res;
}
int main()
{
    ll n,ans=-1,x;
    int k;
    scanf("%lld",&n);
    for(x=(ll)sqrt(n)+1,k=0;k<90&&x>0;k++,x--){
        if(x*x+x*s(x)==n){
            ans=x;
            break;
        }
    }
    printf("%lld",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/stone_fall/article/details/88647483
今日推荐