将 N 个元素平均分成至少 2 个组的方法数
给定一个整数N表示元素的数量,任务是找到将这些元素平均分成组的方法数,使得每个组至少有 2 个元素。
例子:
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.
方法:上述问题可以使用下面给出的蛮力方法来解决。在循环的每次迭代中,我 表示组数。如果N 完全是 可被i整除,因此,元素可以在组之间平均分配。请按照以下步骤解决问题:
- 声明可变方式并将其初始化为0。
- 使用变量i遍历范围[1, N/2]并执行以下任务:
- 检查N是否可以被完全整除 我。
- 如果是,则将方式增加1 。
- 执行上述步骤后,打印ways的值作为答案。
下面是上述方法的实现:
C++
// C++ program for the given approach
#include
using namespace std;
// Function to find the number of ways
int numberofWays(int N)
{
// Variable to store the number of ways
int ways = 0;
int i;
// Loop to find total number of ways
for (i = 1; i <= N / 2; i++) {
if (N % i == 0)
ways++;
}
// Returning the number of ways
return ways;
}
// Driver Code
int main()
{
// Declaring and initialising N
int N = 10;
// Function call
int ans = numberofWays(N);
// Displaying the answer on screen
cout << ans;
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
// Function to find the number of ways
static int numberofWays(int N)
{
// Variable to store the number of ways
int ways = 0;
int i;
// Loop to find total number of ways
for (i = 1; i <= N / 2; i++) {
if (N % i == 0)
ways++;
}
// Returning the number of ways
return ways;
}
public static void main (String[] args)
{
// Declaring and initialising N
int N = 10;
// Function call
int ans = numberofWays(N);
// Displaying the answer on screen
System.out.print(ans);
}
}
// This code is contributed by hrithikgarg03188
Python3
# Python code for the above approach
# Function to find the number of ways
def numberofWays(N):
# Variable to store the number of ways
ways = 0;
i = None
# Loop to find total number of ways
for i in range(1, (N // 2) + 1):
if (N % i == 0):
ways += 1
# Returning the number of ways
return ways;
# Driver Code
# Declaring and initialising N
N = 10;
# Function call
ans = numberofWays(N);
# Displaying the answer on screen
print(ans);
# This code is contributed by Saurabh Jaiswal
C#
// C# program for the above approach
using System;
class GFG {
// Function to find the number of ways
static int numberofWays(int N)
{
// Variable to store the number of ways
int ways = 0;
int i;
// Loop to find total number of ways
for (i = 1; i <= N / 2; i++) {
if (N % i == 0)
ways++;
}
// Returning the number of ways
return ways;
}
public static void Main(string[] args)
{
// Declaring and initialising N
int N = 10;
// Function call
int ans = numberofWays(N);
// Displaying the answer on screen
Console.WriteLine(ans);
}
}
// This code is contributed by ukasp.
Javascript
输出
3
时间复杂度: O(N)
辅助空间: O(1)