Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the output always show 0 as LCM?

  • https://github.com/mehedihasrifat

  • Please correct my mistake**

  • How can I solve this issue?

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • Did I do something wrong here?**

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

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading