forked from SrajanAgrawal/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCM.cpp
More file actions
46 lines (41 loc) · 709 Bytes
/
LCM.cpp
File metadata and controls
46 lines (41 loc) · 709 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// C++ program to find LCM of First N Natural Numbers.
#include <bits/stdc++.h>
#define MAX 100000
using namespace std;
vector<bool> isPrime (MAX, true);
// utility function for sieve of sieve of Eratosthenes
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;
}
}
// Function to find LCM of first n Natural Numbers
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;
}
// Driver code
int main()
{
// build sieve
sieve();
int N = 7;
// Function call
cout << LCM(N);
return 0;
}