Mehedi Hasan Rifat
Mehedi Hasan Rifat

Reputation: 3

Why does the output always show 0 as LCM?

I have been trying to debug this code but ultimately I can't. Please help me, I'm totally new to this platform.

This picture shows the following code

/*
Written by Mehedi Hasan Rifat
Written on October 2, 2022
*/

#include <stdio.h>

int main()
{
    int a, b, t, gcd, lcm;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    if (a == 0)
        gcd = b;
    else if (b == 0)
        gcd = a;
    else
    {
        while (b != 0)
        {
            t = b;
            b = a % b;
            a = t;
        }

        gcd = a;
    }

    lcm = (a * b) / gcd;

    printf("LCM: %d\n", lcm);

    return 0;
}

Upvotes: 0

Views: 99

Answers (1)

As jasonharper says in the comment, when you finished the gcd calculation, b will be always zero.

One quick fix is to add

int original_a = a;
int original_b = b;

and calculate lcm using:

lcm = (original_a * original_b) / gcd;

Or just use the __gcd() function in the <algorithm> library.

#include <algorithm>

int main()
{
    ...
    lcm = (a * b) / std::__gcd(a, b);
}

Upvotes: 1

Related Questions