3E A Simple Problem —— 数论

题目

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

题解

解题思路

我们先来推导一下
(y^2 = n +x^2)
(n = y^2 - x^2)
(n = (y - x)(y + x))
(n = ab)
(a = y - x, b = y + x)
(x = (b - a) / 2)
所以,我们枚举n的因数,再找x的最小值

代码

#include <cstdio>
#include <algorithm>
using namespace std;
const int M = 0x7fffffff;
int t, n, ans;
int main() {
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        ans = M;
        for(int i = 1; i * i <= n; i++)
            if (!(n % i) && !((n/i - i) % 2) && (n/i - i) / 2)
                ans = min(ans, (n/i - i) / 2);
        if (ans == M) puts("-1");
        else printf("%d
", ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Z8875/p/12952784.html