In: Computer Science
Write a C++ program to find least common multiple (LCM) of two, three and four integer values. The integer values are entered from the keyboard and the outputs are printed to the console. The LCM of two, three and four integer values are computed using Prime factorization method.
You have to use arrays to hold input values and use functions/methods to get data from the keyboard, display output to the console, calculate LCM using Prime factorization method. Your program should tell to the user that how many values they need to enter (more than 1 and less than 5) and they need to enter input values from 2 to 100. If 2 values (v1,v2) are entered by the user, then the program should compute the LCM of both values. For example, if 3 values (v1, v2, v3) are entered, then the program should be computed and displayed the following:
If 4 values (v1, v2, v3, v4) are entered, then the program should be computed and displayed the following:
// C++ program to find LCM of n elements
#include <bits/stdc++.h>
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()
{
printf("Enter values between 1 and 5: ");
int n;
int i;
scanf("%d",&n);
if(n==2 && n==3 && n==4 &&
n==5)
{
int arr[n];
printf("Enter elements of array between 2 and
100");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
if(arr[i]<=2&&
arr[i]>100)
{
}
else
printf("enter values between 1 and
100 only");
exit(0);
}
printf("%lld", findlcm(arr, n));
}
return 0;
}