Divide first N natural numbers into 3 equal sum subsets
Last Updated :
28 Mar, 2022
Given an integer N, the task is to check whether the elements from the range [1, N] can be divided into three non-empty equal sum subsets. If possible then print Yes else print No.
Examples:
Input: N = 5
Output: Yes
The possible subsets are {1, 4}, {2, 3} and {5}.
(1 + 4) = (2 + 3) = (5)
Input: N = 3
Output: No
Approach: There are two cases:
- If N ? 3: In this case, it is not possible to divide the elements in the subsets that satisfy the given condition. So, print No.
- If N > 3: In this case, it is only possible when the sum of all the elements of the range [1, N] is divisible by 3 which can be easily calculated as sum = (N * (N + 1)) / 2. Now, if sum % 3 = 0 then print Yes else print No.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
bool possible( int n)
{
if (n > 3) {
int sum = (n * (n + 1)) / 2;
if (sum % 3 == 0) {
return true ;
}
}
return false ;
}
int main()
{
int n = 5;
if (possible(n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.math.*;
class GFG
{
public static boolean possible( int n)
{
if (n > 3 )
{
int sum = (n * (n + 1 )) / 2 ;
if (sum % 3 == 0 )
{
return true ;
}
}
return false ;
}
public static void main(String[] args)
{
int n = 5 ;
if (possible(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def possible(n) :
if (n > 3 ) :
sum = (n * (n + 1 )) / / 2 ;
if ( sum % 3 = = 0 ) :
return True ;
return False ;
if __name__ = = "__main__" :
n = 5 ;
if (possible(n)) :
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG
{
public static bool possible( int n)
{
if (n > 3)
{
int sum = (n * (n + 1)) / 2;
if (sum % 3 == 0)
{
return true ;
}
}
return false ;
}
static public void Main ()
{
int n = 5;
if (possible(n))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function possible(n)
{
if (n > 3)
{
let sum = parseInt((n * (n + 1)) / 2);
if (sum % 3 == 0)
{
return true ;
}
}
return false ;
}
let n = 5;
if (possible(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...