Finding LCM/SCM of two integer numbers
Program to find the Least Common Multiple (LCM), also called the smallest common multiple between the two numbers entered by the user.
Learning Objectives
- Finding LCM/SCM of two numbers by successive subtraction of smaller number from the larger one until they are equal to get the HCF first and then deducing LCM by x*y/HCF(x,y).
Source Code
|
|
Related ( ? ) : |
Run Output
Code Understanding
int x,y; cout<<“Enter two numbers separated by space: “; cin>>x>>y;
Two numbers are collected from the user.
int a=x,b=y;
The original numbers are maintained in x and y and new numbers a and b are created so that they can be used for calculating HCF first which is a process in which values of a and b would be modified during iteration.
while(a != b) { if(a>b) a=a-b; else b=b-a;}
This is HCF finding loop as explained in #2871 .
cout<<“LCM/SCM of “<<x<<” & “<<y<<” = “<< x*y/a;
Here we calculate and print the LCM using the formula n1*n2/HCF(n1,n2);
Notes
- Finding LCM is useful in real life for economizing between choices when multiple variables are present for a goal.
Common Errors
- Student may forget to save the original variables and find the LCM without saving them. For example in above example doing a*b/a will not give the right result. It will give HCF only.
Suggested Filename(s): lcm-scm.cpp
Created: 20-Jan-2018 23:39 | Updated: 21-Jan-2018 00:07|
