给定两个数组,使得第一个数组包含小于或等于k的整数n的倍数,类似地,第二个数组包含小于或等于k的整数m的倍数。
任务是找到数组之间公共元素的数量。
例子:
Input :n=2 m=3 k=9
Output : 1
First array would be = [ 2, 4, 6, 8 ]
Second array would be = [ 3, 6, 9 ]
6 is the only common element
Input :n=1 m=2 k=5
Output : 2
方法 :
找到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))))