CodeForces - 233B Non-square Equation 数学+一元二次方程+配方

题意

给你一个一元二次方程 x 2 + s ( x ) · x n = 0 s ( x ) 表示,x的各数位之和,
例如:
s ( 11 ) = 1 + 1 = 2
s ( 123 ) = 1 + 2 + 3 = 6
s ( 256 ) = 2 + 5 + 6 = 13
接下来,给你一个正整数n,让你求正整数 x!存在输出x,不存在就输出-1;
真心数学题。

分析:

(0) x 2 + s ( x ) · x n = 0

(1) x 2 + s ( x ) · x n + s ( x ) 2 4 = s ( x ) 2 4

(2) ( x + s ( x ) 2 ) 2 = s ( x ) 2 4 + n

(3) x + s ( x ) 2 = s ( x ) 2 4 + n

(4) x = s ( x ) 2 4 + n s ( x ) 2
高中学习过的一元二次方程的配方~
接下来,分析数据, 1 n 10 18
(0) x 2 + s ( x ) · x n = 0
(5) x 2 + s ( x ) · x = n
方程0 —>>方程5 不解释;
由方程5得: x 2 n 数量级相同
即: 1 x 2 10 18
即: 1 x 10 18 1 / 2 = 10 9
即:x的最大值为999999999(9个9)
那么: s ( x ) 的最大值为 9 9 = 81 ,最小值为 1
综上:结合方程4 ,n为给定值, s ( x ) 遍历区间 [ 1 , 81 ] ,只有x为未知量,分别求解出81个x,带入原方程0中,判断下就ok了!
重新上了一遍高中的数学课。。。。

代码:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <iomanip>
#define maxn 100005
#define ll long long
#define debug cout<<"***********"<<endl;
using namespace std;

int sumDigit(ll n){
    int sum = 0;
    while(n){
        sum += n%10;
        n /= 10;
    }
    return sum;
}

int main(){
    ll n;cin>>n;
    bool flag = false;
    ll sumX = 0;
    for(int i = 1; i < 82; i++){
        sumX = sqrt( (double)i*i/4 + n) - i/2;
        if(sumX * sumX + sumDigit(sumX)*sumX - n == 0){
            flag = true;
            break;
        }
    }
    if(flag){
        cout<<sumX<<endl;
    }
    else{
        cout<<"-1"<<endl;
    }
    return 0;
}

加油少年!

猜你喜欢

转载自blog.csdn.net/shensiback/article/details/80101232