My code is not working. Write a C program to find GCD and LCM of ‘n’ numbers, with n being the input from user

207 Views Asked by At

I thought of declaring the variables first, and then finding the gcd and lcm. But when I tried to run, my code is not working. And the VS code is not even showing the errors. I am posting my code here:

#include <stdio.h>
int gcd(int a, int b)
{
    for (int j = 1; j <= a && j <= b; ++j)
    {
         if (a % j == 0 && b % j==0)
            return j;
    }
}
int main ()
{
    int i, n, pro=1, g, t, lcm;
    int num[n];
    printf ("Enter the no. of numbers: ");
    scanf ("%d", &n);
    for (i = 0; i <= n-1; i++)
    {
        printf ("Enter the number: ");
        scanf ("%d", &num[i]);
    }

    g = gcd (num[0], num[1]);

    for (t=2; t <= n; t++)
        g = gcd(num[t], g);

    for (i=0; i <= n-1; i++)
        pro = pro*num[i];

    lcm = pro/g;
    printf ("GCD is %d\n", g);
    printf ("LCM is %d", lcm);
    return 0;
}
1

There are 1 best solutions below

2
Utk On

Well, I tried doing it again. The problem with my code was that the return j was in the loop, and thus, it was returning the value of j instead of giving the value of g.

The corrected code:

#include <stdio.h>
int gcd(int a, int b)
{
    int g;
    for (int j = 2; j <= a && j <= b; ++j)
    {
        if (a % j == 0 && b % j==0)
        g = j;
    }
    return g;
}
int main ()
{
    int i, n, pro=1, g, t, lcm;
    
    printf ("Enter the no. of numbers: ");
    scanf ("%d", &n);
    int num[n];
    for (i = 0; i <= n-1; i++)
    {
        printf ("Enter the number: ");
        scanf ("%d", &num[i]);
    }

    g = gcd (num[0], num[1]);

    for (t=2; t <= n; t++)
        g = gcd(num[t], g);

    for (i=0; i <= n-1; i++)
        pro = pro*num[i];

    lcm = pro/g;
    printf ("GCD is %d\n", g);
    printf ("LCM is %d", lcm);
    return 0;
}