Skip to content

Commit 10b1f34

Browse files
committed
Algo for finding LCM of array Added
1 parent 984b281 commit 10b1f34

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

math/lcm_of_array.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// C++ program to find LCM of n elements
2+
// Author Bharat Reddy
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
typedef long long int ll;
8+
9+
10+
int gcd(int a, int b)
11+
{
12+
if (b == 0)
13+
return a;
14+
return gcd(b, a % b);
15+
}
16+
17+
// Returns LCM of array elements
18+
ll findlcm(int arr[], int n)
19+
{
20+
21+
ll ans = arr[0];
22+
23+
for (int i = 1; i < n; i++)
24+
ans = (((arr[i] * ans)) /
25+
(gcd(arr[i], ans)));
26+
27+
return ans;
28+
}
29+
30+
int main()
31+
{
32+
int n;
33+
cout<<"Enter size of array : ";
34+
cin>>n;
35+
int a[n];
36+
cout<<"Enter elements of array"<<endl;
37+
int i;
38+
for(i=0;i<n;i++)
39+
cin>>a[i];
40+
printf("%lld\n", findlcm(a, n));
41+
return 0;
42+
}

0 commit comments

Comments
 (0)