Given N and D, find if it is possible to make two sets from first N natural numbers such that the difference between the sum of 2 sets(individually) is D.
Examples :
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
Approach :
Let s1 and s2 be the two sets.
Here we know that
sum(s1) + sum(s2) = N*(N+1)/2 and
sum(s1) – sum(s2) = D
Adding above 2 equations, we get
2*sum(s1) = N*(N+1)/2 + D
If sum(S1) and sum(S2) are integers, then only we can split the first N natural numbers into two sets. For that N*(N+1)/2 + D must be an even number.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool check( int N, int D)
{
int temp = (N * (N + 1)) / 2 + D;
return (temp % 2 == 0);
}
int main()
{
int N = 5;
int M = 7;
if (check(N, M))
cout << "yes" ;
else
cout << "no" ;
return 0;
}
|
C
#include <stdio.h>
#include <stdbool.h>
bool check( int N, int D)
{
int temp = (N * (N + 1)) / 2 + D;
return (temp % 2 == 0);
}
int main()
{
int N = 5;
int M = 7;
if (check(N, M))
printf ( "yes" );
else
printf ( "no" );
return 0;
}
|
Java
class GFG
{
static boolean check( int N, int D)
{
int temp = (N * (N + 1 )) / 2 + D;
return (temp % 2 == 0 );
}
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" );
}
}
|
Python3
def check(N, D):
temp = N * (N + 1 ) / / 2 + D
return ( bool (temp % 2 = = 0 ))
N = 5
M = 7
if check(N, M):
print ( "yes" )
else :
print ( "no" )
|
C#
using System;
class GFG
{
static bool check( int N, int D)
{
int temp = (N * (N + 1)) / 2 + D;
return (temp % 2 == 0);
}
static public void Main ()
{
int N = 5;
int M = 7;
if (check(N, M))
Console.Write( "yes" );
else
Console.Write( "no" );
}
}
|
PHP
<?php
function check( $N , $D )
{
$temp = ( $N * ( $N + 1)) / 2 + $D ;
return ( $temp % 2 == 0);
}
$N = 5;
$M = 7;
if (check( $N , $M ))
echo ( "yes" );
else
echo ( "no" );
|
Javascript
<script>
function check( N, D)
{
let temp = (N * (N + 1)) / 2 + D;
return (temp % 2 == 0);
}
let N = 5;
let M = 7;
if (check(N, M))
document.write( "yes" );
else
document.write( "no" );
</script>
|
Time Complexity: O(1), the code will run in a constant time.
Auxiliary Space: O(1), no extra space is required, so it is a constant.