码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4143 A Simple Problem(数论-水题)

时间:2014-08-11 15:02:52      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   color   os   io   for   ar   

A Simple Problem



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,使得 n+x^2也是完全平方数。


解题思路:

假设y^2=n+x^2 ,那么 (y-x)*(y+x)=n,也就是n的两个因子,只需枚举因子即可。


解题代码:

#include <iostream>
#include <cstdio>
using namespace std;

int n;

void solve(){
    int x=(1<<30);
    for(int i=1;i*i<=n;i++){
        if(n%i!=0) continue;
        if( (i&1) == ( (n/i)&1 ) ){
            if((n/i-i)/2>0 && (n/i-i)/2<x ) x=(n/i-i)/2;
        }
    }
    if( x<(1<<30) ) printf("%d\n",x);
    else printf("-1\n");
}

int main(){
    int t;
    scanf("%d",&t);
    while(t-- >0){
        scanf("%d",&n);
        solve();
    }
    return 0;
}





HDU 4143 A Simple Problem(数论-水题),布布扣,bubuko.com

HDU 4143 A Simple Problem(数论-水题)

标签:des   style   http   color   os   io   for   ar   

原文地址:http://blog.csdn.net/a1061747415/article/details/38492327

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!