📜  从第一个N个自然数开始的和之和可能的两个集合之差为D

📅  最后修改于: 2021-04-24 23:51:54             🧑  作者: Mango

给定N和D,找出是否有可能从前N个自然数中得出两个集合,使得2个集合的总和之间的差(分别)为D.
例子 :

Input  : 5 7
Output : yes
Explanation: Keeping 1 and 3 in one set,
and 2, 4 and 5 are in other set.
Sum of set 1 = 4
Sum of set 2 = 11 
So, the difference D = 7 
Which is the required difference

Input  : 4 5
Output : no

方法 :

C++
// C++ program for implementing
// above approach
#include 
using namespace std;
 
// Function returns true if it is
// possible to split into two
// sets otherwise returns false
bool check(int N, int D)
{   
    int temp = (N * (N + 1)) / 2 + D;
    return (temp % 2 == 0);
}
 
// Driver code
int main()
{
    int N = 5;
    int M = 7;
    if (check(N, M))
        cout << "yes";
    else
        cout << "no";
 
    return 0;
}


Java
// Java program for implementing
// above approach
 
class GFG
{
     
    // Function returns true if it is
    // possible to split into two
    // sets otherwise returns false
    static boolean check(int N, int D)
    {
        int temp = (N * (N + 1)) / 2 + D;
        return (temp % 2 == 0);
    }
     
    // Driver code
    static public void main (String args[])
    {
        int N = 5;
        int M = 7;
        if (check(N, M))
            System.out.println("yes");
        else
            System.out.println("no");
    }
}
 
// This code is contributed by Smitha.


Python3
# Python program for implementing
# above approach
 
# Function returns true if it is
# possible to split into two
# sets otherwise returns false
def check(N, D):
    temp = N * (N + 1) // 2 + D
    return (bool(temp % 2 == 0))
 
# Driver code
N = 5
M = 7
if check(N, M):
    print("yes")
else:
    print("no")
 
# This code is contributed by Shrikant13.


C#
// C# program for implementing
// above approach
using System;
 
class GFG
{
     
    // Function returns true if it is
    // possible to split into two
    // sets otherwise returns false
    static bool check(int N, int D)
    {
        int temp = (N * (N + 1)) / 2 + D;
        return (temp % 2 == 0);
    }
     
    // Driver code
    static public void Main ()
    {
        int N = 5;
        int M = 7;
        if (check(N, M))
            Console.Write("yes");
        else
            Console.Write("no");
    }
}
 
// This code is contributed by Ajit.


PHP


Javascript


输出 :

yes