[HDU] [1108] Least Common Multiple

Problem Description

Loading...

Problem Analysis

A basic way to find the least common multiple
divide the product by the greatest common divisor
As for the method of finding the GCD…
My senior said he’d never heard of this one…
-.-

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include<stdio.h>
int main() {
    int a,b,m;
    while(scanf("%d %d",&a,&b)!=EOF) {
        m=a*b;
        while(a!=b) {
            if(a>b)
                a-=b;
            if(b>a)
                b-=a;
        }
        printf("%d\n",m/a);
    }
    return 0;
}

Then he handed me a faster recursive function
for finding the greatest common divisor

cpp
1
2
3
4
5
6
7
8
 int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}

So the least common multiple can be written as

cpp
1
2
3
4
int lcm(int a,int b)
{
return a/gcd(a,b)*b;
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...