Number of ways to divide a N elements equally into group of at least 2
Last Updated :
27 Jan, 2022
Given an integer N denoting the number of elements, the task is to find the number of ways to divide these elements equally into groups such that each group has at least 2 elements.
Examples:
Input: N = 2
Output: 1
Explanation: There can be only one group.
Input: N = 10
Output: 3
Explanation: There are 3 ways to divide elements:
One group having all the 10 elements.
Two groups where each group has 5 elements.
Five groups where each group has 2 elements.
Approach: The above problem can be solved using the below-given brute force approach. In every iteration of the loop, i represents the number of groups. If N is completely divisible by i, hence, the elements can be equally divided among groups. Follow the steps below to solve the problem:
- Declare variable ways and initialize it by 0.
- Iterate over the range [1, N/2] using the variable i and perform the following tasks:
- Check if N is completely divisible by i.
- If yes, then increment ways by 1.
- After performing the above steps, print the value of ways as the answer.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int numberofWays( int N)
{
int ways = 0;
int i;
for (i = 1; i <= N / 2; i++) {
if (N % i == 0)
ways++;
}
return ways;
}
int main()
{
int N = 10;
int ans = numberofWays(N);
cout << ans;
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static int numberofWays( int N)
{
int ways = 0 ;
int i;
for (i = 1 ; i <= N / 2 ; i++) {
if (N % i == 0 )
ways++;
}
return ways;
}
public static void main (String[] args)
{
int N = 10 ;
int ans = numberofWays(N);
System.out.print(ans);
}
}
|
Python3
def numberofWays(N):
ways = 0 ;
i = None
for i in range ( 1 , (N / / 2 ) + 1 ):
if (N % i = = 0 ):
ways + = 1
return ways;
N = 10 ;
ans = numberofWays(N);
print (ans);
|
C#
using System;
class GFG {
static int numberofWays( int N)
{
int ways = 0;
int i;
for (i = 1; i <= N / 2; i++) {
if (N % i == 0)
ways++;
}
return ways;
}
public static void Main( string [] args)
{
int N = 10;
int ans = numberofWays(N);
Console.WriteLine(ans);
}
}
|
Javascript
<script>
function numberofWays(N)
{
let ways = 0;
let i;
for (i = 1; i <= Math.floor(N / 2); i++) {
if (N % i == 0)
ways++;
}
return ways;
}
let N = 10;
let ans = numberofWays(N);
document.write(ans);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...