From 63a0cfafb1b7ca6a3651b04c66c3c5e792f6bec8 Mon Sep 17 00:00:00 2001 From: sharique191 <55195432+sharique191@users.noreply.github.com> Date: Thu, 17 Oct 2019 19:45:54 +0530 Subject: [PATCH] create lcm of arrays --- syed mubashir/lcm of arrays.cpp | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 syed mubashir/lcm of arrays.cpp diff --git a/syed mubashir/lcm of arrays.cpp b/syed mubashir/lcm of arrays.cpp new file mode 100644 index 0000000..ded9a50 --- /dev/null +++ b/syed mubashir/lcm of arrays.cpp @@ -0,0 +1,38 @@ +// C++ program to find LCM of n elements +#include +using namespace std; + +typedef long long int ll; + +// Utility function to find +// GCD of 'a' and 'b' +int gcd(int a, int b) +{ + if (b == 0) + return a; + return gcd(b, a % b); +} + +// Returns LCM of array elements +ll findlcm(int arr[], int n) +{ + // Initialize result + ll ans = arr[0]; + + // ans contains LCM of arr[0], ..arr[i] + // after i'th iteration, + for (int i = 1; i < n; i++) + ans = (((arr[i] * ans)) / + (gcd(arr[i], ans))); + + return ans; +} + +// Driver Code +int main() +{ + int arr[] = { 2, 7, 3, 9, 4 }; + int n = sizeof(arr) / sizeof(arr[0]); + printf("%lld", findlcm(arr, n)); + return 0; +}