0

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;
}
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Your final computation of `lcm` needs to use the *original* values of `a` and `b`, NOT the values that have been modified by the loop that calculates `gcd`. In particular, `b` is guaranteed to be zero when the loop finishes, so your result cannot be anything other than zero. – jasonharper Oct 02 '22 at 03:23

1 Answers1

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);
}