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:
#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()
{
int
arr[] = { 2, 7, 3, 9, 4 };
int
n
=
sizeof
(arr) /
sizeof
(arr[0]);
printf
(
"%lld"
,
findlcm(arr, n));
return
0;
}
the above-mentioned code is for lcm of an array.
this can be willingly modified by defining the length of array.
that is setting the value of n.
if n = 2 it will take only 2 elements in the array and find lcm if n = 3 then 3 elements and so on.
for any confusion please comment instead of straight downvote.