Search code examples
cdev-c++lcm

L.C.M of two numbers in C


So, here is my code to calculate L.C.M (Least common multiple) without using G.C.D:

int lcm(int x, int y){

    int max = 0, min = 0, ans = 0;

    if(y >= x){
        max = y;
        min = x;    
        if(y % x == 0) return y;
    }else {
        max = x;
        max = y;
        if(x % y == 0) return x;
    }

    for(int i = 1; i <= max ; i++){
        if( (max*i) % min == 0){
            ans = max * i;
            break;
        }
    }

    return ans;
}

and here is the main:

int main(){

    int u, v;

    printf("Input two numbers: ");
    scanf("%d%d", &u, &v);
    puts("");
    printf("LCM(%d, %d): %d",u , v, lcm(u, v));

    return 0;  
}

It works perfectly for inputs like 4 8,7 21 and everything else in which the first number is smaller. An example:

It takes a lot of time to run if the value of first input is higher and does nothing

What am I doing wrong here?

I am using Dev-C++.


Solution

  • In the else statement inside the lcm function, it should be min = y. That was the mistake I was making. Thanks TotallyNoob for pointing it out.