zoukankan      html  css  js  c++  java
  • HDU 4143 A Simple Problem 题解

    题目

    For a given positive integer n, please find the saallest positive integer x that we can find an integer y such that (y^2 = n +x^2).

    输入

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

    输出

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

    样例输入

    2
    2
    3
    

    样例输出

    -1
    1
    

    题解

    (ecause y^2 = n +x^2)

    ( herefore n=y^2-x^2 = (y+x)(y-x))

    所以找到两个数字(a, b), 满足

    1. (a cdot b = n)

    2. ((a+b)%2==0) , 因为((a+b)\%2=(y+x+y-x)\%2=(2cdot y)\%2=0)

    3. (a>b) , 因为(x>0)

    4. ((a-b)\%2==0), 因为((a-b)\%2=(y+x-y+x)\%2=(2cdot x)\%2=0)

    5. (a-b=2 cdot x)最小, 即(x)最小

    因为求的是(a-b)最小且(a cdot b=n), 所以从(sqrt n) 开始遍历, 若满足条件, 更新最小值, 如果没找到, 就输出(-1)

    代码

    #include <cmath>
    #include <cstdio>
    int main() {
        int t;
        scanf("%d", &t);
        while (t--) {
            int n, minv = 0x7f7f7f7f, flag = 0;
            scanf("%d", &n);
            for (int i = 1; i < sqrt(n); i++) {
                if (n % i == 0 && (i + n / i) % 2 == 0 && (n / i - i) % 2 == 0 && (n / i - i) > 0) {
                    flag = 1;
                    if (n / i - i < minv) minv = n / i - i;
                }
            }
            printf("%d
    ", flag ? minv / 2 : -1);
        }
        return 0;
    }
    
  • 相关阅读:
    [LeetCode]Subsets II
    [LeetCode]Subsets
    [LeetCode]Combinations
    [LeetCode]Minimum Window Substring
    [LeetCode]Search a 2D Matrix
    [LeetCode]Edit Distance
    [LeetCode]Simplify Path
    Adaboost算法
    [LeetCode]Text Justification
    31、剑指offer--从1到n整数中1出现次数
  • 原文地址:https://www.cnblogs.com/youxam/p/hdu-4143.html
Copyright © 2011-2022 走看看