zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    数据库之小问题
    网络基础
    react-fiber 解析
    【like-react】手写一个类似 react 的框架
    istat menus 序列号
    Git学习
    JavaScript设计模式与开发实践【第一部分】
    javascript 原生bind方法实现
    requirejs 学习
    mac 安装maven+eclipse
  • 原文地址:https://www.cnblogs.com/shawk/p/12952784.html
Copyright © 2011-2022 走看看