Given two arrays such that the first array contains multiples of an integer n which are less than or equal to k and similarly, the second array contains multiples of an integer m which are less than or equal to k.
The task is to find the number of common elements between the arrays.
Examples:
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
Approach :
Find the LCM of n and m .As LCM is the least common multiple of n and m, all the multiples of LCM would be common in both the arrays. The number of multiples of LCM which are less than or equal to k would be equal to k/(LCM(m, n)).
To find the LCM first calculate the GCD of two numbers using the Euclidean algorithm and lcm of n, m is n*m/gcd(n, m).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int gcd( int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
int lcm( int n, int m)
{
return (n * m) / gcd(n, m);
}
int main()
{
int n = 2, m = 3, k = 5;
cout << k / lcm(n, m) << endl;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int gcd( int a, int b)
{
if (a == 0 )
return b;
return gcd(b % a, a);
}
static int lcm( int n, int m)
{
return (n * m) / gcd(n, m);
}
public static void main(String[] args)
{
int n = 2 , m = 3 , k = 5 ;
System.out.print( k / lcm(n, m));
}
}
|
Python3
def gcd(a, b) :
if (a = = 0 ) :
return b;
return gcd(b % a, a);
def lcm(n, m) :
return (n * m) / / gcd(n, m);
if __name__ = = "__main__" :
n = 2 ; m = 3 ; k = 5 ;
print (k / / lcm(n, m));
|
C#
using System;
class GFG
{
static int gcd( int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm( int n, int m)
{
return (n * m) / gcd(n, m);
}
public static void Main(String[] args)
{
int n = 2, m = 3, k = 5;
Console.WriteLine( k / lcm(n, m));
}
}
|
Javascript
<script>
function gcd(a, b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
function lcm(n, m)
{
return (n * m) / gcd(n, m);
}
var n = 2, m = 3, k = 5;
document.write( parseInt(k / lcm(n, m)));
</script>
|
Time Complexity : O(log(min(n,m)))
Auxiliary Space: O(log(min(n, m)))