奇数凑数问题

You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.

You have to answer t independent test cases.

Input

The first line of the input contains one integer t (1≤t≤105) — the number of test cases.

The next t lines describe test cases. The only line of the test case contains two integers n and k (1≤n,k≤107).

Output

For each test case, print the answer — “YES” (without quotes) if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers and “NO” otherwise.

题意:你有两个整数n和k,你的任务是找出n是否可以表示为k个不同的正奇数的和(感谢有道词典:))。

感受:怎么感觉自己近期越来越不行了。。(这种问题越想越复杂,我都想到了二进制解决,发现还是越来越复杂,我是真的脑残)状态不怎么佳,这道题还是看的我的大佬伙伴的代码,不过倒是很好理解。

思路:我们首先要搞明白k个奇数能够凑成哪几个数,这是主要的思路,我们观察前k个奇数最小能够凑成k2,此后k2 + 2, k2 + 4…
都可以凑出来,那么我们只需要判断给定的 n 是不是范围内的可以凑成的数就可以了。

#include <iostream>

using namespace std;
typedef long long LL;
int main()
{
    int T;cin >> T;
    while(T --)
    {
        LL a, k; cin >> a >> k;
        LL t = k * k;
        if(((LL)a + k) % 2) 
        {
            cout << "NO" << endl;
            continue;
        }
        if(a >= t) cout << "YES" << endl;
        else cout << "NO" << endl;   
    }
    return 0;
}
发布了53 篇原创文章 · 获赞 14 · 访问量 1874

猜你喜欢

转载自blog.csdn.net/weixin_45630535/article/details/105078372