0

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++.

Abhijit
  • 468
  • 8
  • 22

1 Answers1

0

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.

Abhijit
  • 468
  • 8
  • 22
  • OK, it would be nice if you think about it. Good luck and have a lot of fun! – the busybee Oct 07 '19 at 14:37
  • @thebusybee Mark as what? Do you mean "accept"? Why do you want this answer (written by question-OP) to be accepted? Just asking out of curiosity. – Yunnosch Oct 07 '19 at 16:07
  • Because this question will be shown as answered and marked. When you are researching on a problem here on SO, which questions do you click first? With 0 answers, with at least 1 answer, or with a marked answer? Well, that's why. ;-) – the busybee Oct 07 '19 at 17:42