Given a number n such that 1 <= N <= 10^6, the Task is to Find the LCM of First n Natural Numbers.
Examples:
Input : n = 5
Output : 60
Input : n = 6
Output : 60
Input : n = 7
Output : 420
We have discussed a simple solution in below article.
Smallest number divisible by first n numbers
The above solution works fine for single input. But if we have multiple inputs, it is a good idea to use Sieve of Eratosthenes to store all prime factors. As we know if LCM(a, b) = X so any prime factor of a or b will also be the prime factor of âXâ.
- Initialize lcm variable with 1
- Generate a Sieve of Eratosthenes (bool vector isPrime) of length 10^6 (ideally must be equal to no. of digits in factorial)
- Now, for each number in bool vector isPrime, if the number is prime (isPrime[i] is true), find the maximum number which is less than the given number and equal to power of the prime.
- Then multiply this number with lcm variable.
- Repeat step 3 and 4 until prime is less than the given number.
Illustration:
For example, if n = 10
8 will be the first number which is equal to 2^3
then 9 which is equal to 3^2
then 5 which is equal to 5^1
then 7 which is equal to 7^1
Finally, we multiply those numbers 8*9*5*7 = 2520
Below is the implementation of the above idea.
C++
#include <bits/stdc++.h>
#define MAX 100000
using namespace std;
vector<bool> isPrime (MAX, true);
void sieve()
{
for (int i = 2; i * i <= MAX; i++)
{
if (isPrime[i] == true)
for (int j = i*i; j<= MAX; j+=i)
isPrime[j] = false;
}
}
long long LCM(int n)
{
long long lcm = 1;
int i=2;
while(i<=n) {
if(isPrime[i]){
int pp = i;
while (pp * i <= n)
pp = pp * i;
lcm *= pp;
}
i++;
}
return lcm;
}
int main()
{
sieve();
int N = 7;
cout << LCM(N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int MAX = 100000;
static ArrayList<Integer> primes
= new ArrayList<Integer>();
static void sieve()
{
boolean[] isComposite = new boolean[MAX + 1];
for (int i = 2; i * i <= MAX; i++)
{
if (isComposite[i] == false)
for (int j = 2; j * i <= MAX; j++)
isComposite[i * j] = true;
}
for (int i = 2; i <= MAX; i++)
if (isComposite[i] == false)
primes.add(i);
}
static long LCM(int n)
{
long lcm = 1;
for (int i = 0;
i < primes.size() && primes.get(i) <= n;
i++)
{
int pp = primes.get(i);
while (pp * primes.get(i) <= n)
pp = pp * primes.get(i);
lcm *= pp;
lcm %= 1000000007;
}
return lcm;
}
public static void main(String[] args)
{
sieve();
int N = 7;
System.out.println(LCM(N));
}
}
|
Python3
MAX = 100000
primes = []
def sieve():
isComposite = [False]*(MAX+1)
i = 2
while (i * i <= MAX):
if (isComposite[i] == False):
j = 2
while (j * i <= MAX):
isComposite[i * j] = True
j += 1
i += 1
for i in range(2, MAX+1):
if (isComposite[i] == False):
primes.append(i)
def LCM(n):
lcm = 1
i = 0
while (i < len(primes) and primes[i] <= n):
pp = primes[i]
while (pp * primes[i] <= n):
pp = pp * primes[i]
lcm *= pp
lcm %= 1000000007
i += 1
return lcm
sieve()
N = 7
print(LCM(N))
|
C#
using System.Collections;
using System;
class GFG {
static int MAX = 100000;
static ArrayList primes = new ArrayList();
static void sieve()
{
bool[] isComposite = new bool[MAX + 1];
for (int i = 2; i * i <= MAX; i++)
{
if (isComposite[i] == false)
for (int j = 2; j * i <= MAX; j++)
isComposite[i * j] = true;
}
for (int i = 2; i <= MAX; i++)
if (isComposite[i] == false)
primes.Add(i);
}
static long LCM(int n)
{
long lcm = 1;
for (int i = 0;
i < primes.Count && (int)primes[i] <= n;
i++)
{
int pp = (int)primes[i];
while (pp * (int)primes[i] <= n)
pp = pp * (int)primes[i];
lcm *= pp;
lcm %= 1000000007;
}
return lcm;
}
public static void Main()
{
sieve();
int N = 7;
Console.WriteLine(LCM(N));
}
}
|
Javascript
<script>
let MAX = 100000;
let primes = [];
function sieve()
{
let isComposite = new Array(MAX + 1);
isComposite.fill(false);
for (let i = 2; i * i <= MAX; i++)
{
if (isComposite[i] == false)
for (let j = 2; j * i <= MAX; j++)
isComposite[i * j] = true;
}
for (let i = 2; i <= MAX; i++)
if (isComposite[i] == false)
primes.push(i);
}
function LCM(n)
{
let lcm = 1;
for (let i = 0;
i < primes.length && primes[i] <= n;
i++)
{
let pp = primes[i];
while (pp * primes[i] <= n)
pp = pp * primes[i];
lcm *= pp;
lcm %= 1000000007;
}
return lcm;
}
sieve();
let N = 7;
document.write(LCM(N));
</script>
|
PHP
<?php
$MAX = 100000;
$primes = array();
function sieve()
{
global $MAX, $primes;
$isComposite = array_fill(0, $MAX, false);
for ($i = 2; $i * $i <= $MAX; $i++)
{
if ($isComposite[$i] == false)
for ($j = 2; $j * $i <= $MAX; $j++)
$isComposite[$i * $j] = true;
}
for ($i = 2; $i <= $MAX; $i++)
if ($isComposite[$i] == false)
array_push($primes, $i);
}
function LCM($n)
{
global $MAX, $primes;
$lcm = 1;
for ($i = 0; $i < count($primes) &&
$primes[$i] <= $n; $i++)
{
$pp = $primes[$i];
while ($pp * $primes[$i] <= $n)
$pp = $pp * $primes[$i];
$lcm *= $pp;
$lcm %= 1000000007;
}
return $lcm;
}
sieve();
$N = 7;
echo LCM($N);
?>
|
Time Complexity: O(n2)
Auxiliary Space: O(n)
Another Approach:
The idea is that if the number is less than 3 then return number. If the number is greater than 2 then find LCM of n,n-1
- Lets say x=LCM(n,n-1)
- again x=LCM(x,n-2)
- again x=LCM(x,n-3) …
- .
- .
- again x=LCM(x,1) …
now the result is x.
For finding LCM(a,b) we use a function hcf(a,b) whichwill return HCF of (a,b)
We know that LCM(a,b)= (a*b)/HCF(a,b)
Illustration:
For example, if n = 7
function call lcm(7,6)
now lets say a=7 , b=6
Now , b!= 1 Hence
a=lcm(7,6) = 42 and b=6-1=5
function call lcm(42,5)
a=lcm(42,5) = 210 and b=5-1=4
function call lcm(210,4)
a=lcm(210,4) = 420 and b=4-1=3
function call lcm(420,3)
a=lcm(420,3) = 420 and b=3-1=2
function call lcm(420,2)
a=lcm(420,2) = 420 and b=2-1=1
Now b=1
Hence return a=420
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
int hcf(int a, int b)
{
if (b == 0)
return a;
return hcf(b, a % b);
}
int findlcm(int a,int b)
{
if (b == 1)
return a;
a = (a * b) / hcf(a, b);
b -= 1;
return findlcm(a, b);
}
int main()
{
int n = 7;
if (n < 3)
cout << n;
else
cout << findlcm(n, n - 1);
return 0;
}
|
Java
public class Main
{
static int hcf(int a, int b)
{
if (b == 0)
return a;
return hcf(b, a % b);
}
static int findlcm(int a,int b)
{
if (b == 1)
return a;
a = (a * b) / hcf(a, b);
b -= 1;
return findlcm(a, b);
}
public static void main(String[] args)
{
int n = 7;
if (n < 3)
System.out.print(n);
else
System.out.print(findlcm(n, n - 1));
}
}
|
Python3
def hcf(a, b):
if (b == 0):
return a
return hcf(b, a % b)
def findlcm(a, b):
if (b == 1):
return a
a = (a * b) // hcf(a, b)
b -= 1
return findlcm(a, b)
n = 7
if (n < 3):
print(n)
else:
print(findlcm(n, n - 1))
|
C#
using System;
class GFG {
static int hcf(int a, int b)
{
if (b == 0)
return a;
return hcf(b, a % b);
}
static int findlcm(int a,int b)
{
if (b == 1)
return a;
a = (a * b) / hcf(a, b);
b -= 1;
return findlcm(a, b);
}
static void Main() {
int n = 7;
if (n < 3)
Console.Write(n);
else
Console.Write(findlcm(n, n - 1));
}
}
|
Javascript
<script>
function hcf(a, b)
{
if (b == 0)
return a;
return hcf(b, a % b);
}
function findlcm(a,b)
{
if (b == 1)
return a;
a = (a * b) / hcf(a, b);
b -= 1;
return findlcm(a, b);
}
let n = 7;
if (n < 3)
document.write(n);
else
document.write(findlcm(n, n - 1));
</script>
|
Time complexity : O(nlog n)
Auxiliary Space: O(1)
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
23 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...