Using C and start only with #include<stdio.h> int main(). The least common multi
ID: 3633360 • Letter: U
Question
Using C and start only with #include<stdio.h> int main().
The least common multiple (lcm) of a sequence of integers is the smallest positive integer that is a multiple of each of them. For example, lcm(6, 10, 15) is 30, as it is divisible by 6, 10, and 15, and no smaller than 30 is. If any of the integers in the sequence is zero, then the lcm of that sequence is defined to be zero.
Write a program that prompts the user for length of a sequence and then for a sequence of integers of that length, and finds the lcm of that sequence.
Your program should include the function int LCM2 (int, int) that computes the lcm of two integers. Note that there are many ways to compute the lcm of two integers a and b, and you can use any you like. One way is to find the lowest multiple of a that is divisible by b. Hint: The lcm of three integers a, b, c is equal to LCM2(LCM2(a, b),c).
Ex)
Length of sequence:(output) 4(input)
Sequence:(output) 3 7 3 -5(input)
LCM: 105(output)
Length of sequence:(output) 5(input)
Sequence:(output) 0 2 4 6 8(input)
LCM: 0(output)
Length of sequence:(output) 4(input)
Sequence:(output) 10 20 30 40(input)
LCM: 120(output)
Length of sequence:(output) 3(input)
Sequence:(output) 48 0 36(input)
LCM: 0
Length of sequence:(output) 1(input)
Sequence:(output) 27(input)
LCM: 27(output)
Explanation / Answer
# include<stdio.h>
int LCM2 (int, int);
int HCF2 (int, int);
int main()
{
int a[10];
int n,i,LCM=1;
printf("Enter the length of the sequence:");
scanf("%d", &n);
printf("Enter the sequence:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++){
LCM=LCM2(LCM,a[i]);
}
printf(" LCM : %d",LCM);
return(0);
}
int LCM2 (int a, int b)
{
int small,big,HCF,LCM;
if (a ==0 || b==0)
return (0);
small = (a<b)?a:b;
big= a*b/small;
if((big%small) == 0)
{
if (big<0)
big = -big;
return (big);
}
HCF = HCF2(a,b);
LCM = (a * b)/HCF;
if (LCM<0)
LCM =-LCM;
return (LCM);
}
int HCF2( int a, int b)
{
int small;
small =(a<b)?a:b;
for (;small>=0;small--)
{
if((a%small ==0 ) && (b%small ==0))
return (small);
}
return (1);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.