📌  相关文章
📜  计算包含N和M的倍数的两个数组中的公共元素

📅  最后修改于: 2021-06-25 22:52:44             🧑  作者: Mango

给定两个数组,使得第一个数组包含小于或等于k的整数n的倍数,类似地,第二个数组包含小于或等于k的整数m的倍数。
任务是找到数组之间公共元素的数量。
例子:

方法 :
找到n和m。作为LCM的LCM是n和m的最小公倍数,LCM的所有的倍数将是常见的两个阵列。小于或等于k的LCM的倍数等于k /(LCM(m,n))。
要找到LCM,首先使用欧几里得算法和n的lcm计算两个数字的GCD,则m为n * m / gcd(n,m)。
下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
 
using namespace std;
 
// Recursive function to find
// gcd using euclidean algorithm
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Function to find lcm
// of two numbers using gcd
int lcm(int n, int m)
{
    return (n * m) / gcd(n, m);
}
 
// Driver code
int main()
{
    int n = 2, m = 3, k = 5;
 
    cout << k / lcm(n, m) << endl;
 
    return 0;
}


Java
// Java implementation of the above approach
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG
{
 
// Recursive function to find
// gcd using euclidean algorithm
static int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Function to find lcm
// of two numbers using gcd
static int lcm(int n, int m)
{
    return (n * m) / gcd(n, m);
}
 
// Driver code
public static void main(String[] args)
{
    int n = 2, m = 3, k = 5;
 
    System.out.print( k / lcm(n, m));
}
}
 
// This code is contributed by mohit kumar 29


Python3
# Python3 implementation of the above approach
 
# Recursive function to find
# gcd using euclidean algorithm
def gcd(a, b) :
 
    if (a == 0) :
        return b;
         
    return gcd(b % a, a);
 
# Function to find lcm
# of two numbers using gcd
def lcm(n, m) :
 
    return (n * m) // gcd(n, m);
 
 
# Driver code
if __name__ == "__main__" :
 
    n = 2; m = 3; k = 5;
 
    print(k // lcm(n, m));
 
# This code is contributed by AnkitRai01


C#
// C# implementation of the above approach
using System;
     
class GFG
{
 
// Recursive function to find
// gcd using euclidean algorithm
static int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Function to find lcm
// of two numbers using gcd
static int lcm(int n, int m)
{
    return (n * m) / gcd(n, m);
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 2, m = 3, k = 5;
 
    Console.WriteLine( k / lcm(n, m));
}
}
 
// This code is contributed by Princi Singh


Javascript


输出:
0

时间复杂度: O(log(min(n(n,m))))

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。