给定两个质数N和M ,任务是找到两个给定质数的最小公倍数(LCM)。
例子:
Input: N = 3, M = 7
Output: 21
Explanation:
The least numbers greater than equals to 3 and 7 which is a multiple of 3 and 7 is 21.
Input: N = 5, M = 5
Output: 5
Explanation:
The least numbers greater than equals to 5 and 5 which is a multiple of 5 and 5 is 5.
方法:我们知道两个数的乘积等于它们的最大公除数(GCD)和最小公倍数(LCM)的乘积。因此,两个给定质数的LCM可以由下式给出: 。
由于GCD两个不同的质数为1,因此 ,如果两个给定的数字相同,则LCM就是数字本身。
下面是上述方法的实现:
C++
// C++ Program to find LCM of two
// prime numbers
#include
using namespace std;
// Function to return the LCM of two
// prime numbers
int findLCMPrime(int a, int b)
{
// If the two numbers are equal
// then return any one of a and b
if (a == b) {
return a;
}
// Else return product of numbers
return a * b;
}
// Driver code
int main()
{
// Given two numbers
int a = 3, b = 5;
// Function Call
cout << findLCMPrime(a, b);
return 0;
}
Java
// Java Program to find LCM of two
// prime numbers
class GFG{
// Function to return the LCM of two
// prime numbers
static int findLCMPrime(int a, int b)
{
// If the two numbers are equal
// then return any one of a and b
if (a == b)
{
return a;
}
// Else return product of numbers
return a * b;
}
// Driver code
public static void main (String[] args)
{
// Given two numbers
int a = 3, b = 5;
// Function Call
System.out.println(findLCMPrime(a, b));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 program to find LCM of two
# prime numbers
# Function to return the LCM of two
# prime numbers
def findLCMPrime(a, b):
# If the two numbers are equal
# then return any one of a and b
if (a == b):
return a;
# Else return product of the numbers
return a * b;
# Driver code
if __name__ == "__main__":
# Given two numbers
a = 3; b = 5;
# Function Call
print(findLCMPrime(a, b));
# This code is contributed by AnkitRai01
C#
// C# program to find LCM of two prime numbers
using System;
class GFG{
// Function to return the LCM of two
// prime numbers
static int findLCMPrime(int a, int b)
{
// If the two numbers are equal
// then return any one of a and b
if (a == b)
{
return a;
}
// Else return product of numbers
return a * b;
}
// Driver code
public static void Main (string[] args)
{
// Given two numbers
int a = 3, b = 5;
// Function Call
Console.WriteLine(findLCMPrime(a, b));
}
}
// This code is contributed by AnkitRai01
Javascript
输出
15
时间复杂度: O(1)