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

这篇博客介绍了如何解决CodeForces上的一个数学问题,涉及一元二次方程和数位和的概念。通过配方方法转换方程,分析数据范围,确定x的可能值,并给出代码实现。
摘要由CSDN通过智能技术生成

题意

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

分析:

x2+s(x)xn=0(0) (0) x 2   +   s ( x ) · x   −   n   =   0

x2+s(x)xn+s(x)24=s(x)24(1) (1) x 2 + s ( x ) · x − n + s ( x ) 2 4 = s ( x ) 2 4

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

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

x=s(x)24+ns(x)2(4) (4) x = s ( x ) 2 4 + n − s ( x ) 2
高中学习过的一元二次方程的配方~
接下来,分析数据, 1n1018 1   ≤   n   ≤   10 18
x2+s(x)xn=0(0) (0) x 2   +   s ( x ) · x   −   n   =   0
x2+s(x)x=n(5) (5) x 2   +   s ( x ) · x   =   n  
方程0 —>>方程5 不解释;
由方程5得: x2 x 2 n n 数量级相同
即:1x21018
即: 1x10181/2=109 1   ≤   x ≤   10 18 1 / 2 = 10 9
即:x的最大值为999999999(9个9)
那么: s(x) s ( x ) 的最大值为 99=81 9 ∗ 9 = 81 ,最小值为 1 1
综上:结合方程4 ,n为给定值,s(x)遍历区间 [1,81] [ 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;
}

加油少年!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值