hdu 4143 A Simple Problem(数学)

本文解析了一道名为ASimpleProblem的ACM编程题,通过数学变换简化了原问题,采用因子化简的方法来避免暴力求解导致的时间超限。文章详细介绍了如何将原方程转换并简化,最终通过优化后的算法找到了最小的正整数解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

http://acm.split.hdu.edu.cn/showproblem.php?pid=4143

A Simple Problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 5326    Accepted Submission(s): 1385


Problem Description
For a given positive integer n, please find the smallest positive integer x that we can find an integer y such that y^2 = n +x^2.
 

Input
The first line is an integer T, which is the the number of cases.
Then T line followed each containing an integer n (1<=n <= 10^9).
 

Output
For each integer n, please print output the x in a single line, if x does not exit , print -1 instead.
 

Sample Input
  
2 2 3
 

Sample Output
  
-1 1
 

Author
HIT
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   4144  4147  4145  4146  4148 
 


严格来说不算是一道数学题,主要在于因子化简的思路,避免暴力答案超时

对题中算式进行化简为:n=(x+y)*(x-y),设i=x+y,则y=(i+j)/2,x=y-i

x+y=n/i和x=y-i联立,消去y,则x=[(n/i)-i]/2

这样二重循环降到遍历一次,当y=0时,x^2=n,所以上限为n的算数平方根。再根据x>0,进行优化


还有一个容易忽视的地方,x为最小正整数,所以遍历从大到小

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main(){
    int T;
    int n,i,j,k,x,y;
    int ans;
    scanf("%d",&T);
    while(T--){
        ans=-1;
        scanf("%d",&n);
        for(i=sqrt(n);i>0;i--){
            if(n%i==0&&(n/i-i)%2==0&&(n/i-i)/2>0){///确保x为整数,并且为正数
                ans=(n/i-i)/2;
                break;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值