给定两个整数N和M表示男孩和女孩的数量,任务是将它们排列在相同大小的不同行中,以使每行包含尽可能多的学生,并且每行应包含男孩或女孩。
注意:任何行都不能同时包含男孩和女孩。
例子:
Input: N = 4, M = 2
Output: 2
Explanation:
The following order of arrangement satisfies the given conditions:
1st Row: B1, B2
2nd Row: B3, B4
3rd Row: G1, G2
Clearly, every row has either boys or girls.
Input: N = 6, M = 6
Output: 6
Explanation:
The following order of arrangement satisfies the given conditions:
1st Row: B1, B2, B3, B4, B5, B6
2nd Row: G1, G2, G3, G4, G5, G6
方法:按照以下步骤解决问题
- 由于每行可以包含男孩或女孩,并且所有行的大小必须相同,因此最佳的排列方式是在每行中放置(N,M)个元素的更大公约数。
- 因此,将GCD(N,M)打印为必需的答案。
下面是上述方法的实现:
C++14
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to calculate
// GCD of two numbers
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Function to count maximum persons
// that can be placed in a row
int maximumRowValue(int n, int m) { return gcd(n, m); }
// Driver Code
int main()
{
// Input
int N = 4;
int M = 2;
// Function to count maximum
// persons that can be placed in a row
cout << maximumRowValue(N, M);
}
Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG
{
// Function to calculate
// GCD of two numbers
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Function to count maximum persons
// that can be placed in a row
static int maximumRowValue(int n, int m) {
return gcd(n, m);
}
// Driver Code
public static void main(String args[])
{
// Input
int N = 4;
int M = 2;
// Function to count maximum
// persons that can be placed in a row
System.out.print(maximumRowValue(N, M));
}
}
// This code is contributed by SURENDRA_GANGWAR.
Python3
# Python3 Program to implement
# the above approach
# Function to calculate
# GCD of two numbers
def gcd(a, b):
if (b == 0):
return a
return gcd(b, a % b)
# Function to count maximum persons
# that can be placed in a row
def maximumRowValue(n, m):
return gcd(n, m)
# Driver Code
if __name__ == '__main__':
# Input
N = 4
M = 2
# Function to count maximum
# persons that can be placed in a row
print (maximumRowValue(N, M))
# This code is contributed by mohit kumar 29.
C#
// C# Program to implement
// the above approach
using System;
class GFG
{
// Function to calculate
// GCD of two numbers
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Function to count maximum persons
// that can be placed in a row
static int maximumRowValue(int n, int m) { return gcd(n, m); }
// Driver Code
public static void Main(String[] args)
{
// Input
int N = 4;
int M = 2;
// Function to count maximum
// persons that can be placed in a row
Console.WriteLine(maximumRowValue(N, M));
}
}
// This code is contributed by code_hunt.
Javascript
输出:
2
时间复杂度: O(log N)
辅助空间: O(1)