简体   繁体   中英

Finding least common multiples by prime factorization

I can't figure out how to find LCM using prime factorization. I managed to find prime factors of both numbers and put them in arrays, but I have no idea how to chose which of them should be used to calculate LCM.

int lcm(int a, int b)
{
int arrA[100], arrB[100], x, y, z;
x=2;
y=0;
while(a>1)
{
    while(a%x==0)
    {
        a=a/x;
        arrA[y]=x;
        cout<<arrA[y]<<endl;
        y++;
    }
    x++;
}
x=2;
z=0;
    while(b>1)
{
    while(b%x==0)
    {
        b=b/x;
        arrB[z]=x;
        cout<<arrB[z]<<endl;
        z++;
    }
    x++;
}
}

You can calculate the GCD by multiplying all common factors.
Eg. if a is 2*2*2*3*5 and b is 2*2*5*5,
the common factors are 2*2*5, so the GCD is 20.

The LCM of two numbers a and b is (a*b)/gcd(a,b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM