📌  相关文章
📜  将N个男孩和M个女孩放在不同的行中,以使每行放置的人数最大化

📅  最后修改于: 2021-04-17 18:00:09             🧑  作者: Mango

给定两个整数NM表示男孩和女孩的数量,任务是将它们排列在相同大小的不同行中,以使每行包含尽可能多的学生,并且每行应包含男孩或女孩。
注意:任何行都不能同时包含男孩和女孩。

例子:

方法:按照以下步骤解决问题

  • 由于每行可以包含男孩或女孩,并且所有行的大小必须相同,因此最佳的排列方式是在每行中放置(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)