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

📅  最后修改于: 2021-10-26 05:55:03             🧑  作者: 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,m)))