0

Im trying to find this GCD and LCM in C

GCD example :

Input 1 : 20

Input 2 : 15

Num1 : 20 = 2 x 2 x 5

Num2 : 15 = 3 x 5

GCD = 5

and

LCM example :

Input 1 : 20

Input 2 : 15

15 : 15, 30, 45, 60, 75, 90, 105, 120, 135, ...

20 : 20, 40, 60, 80, 100, 120, 140, ...

Common Multiple = 60, 120, ...

LCM = 60

How do i print

Num1 : 20 = 2 x 2 x 5

Num2 : 15 = 3 x 5

inside

#include <stdio.h>
int main()
{
    int n1, n2, i, gcd;

    printf("Enter two integers: ");
    scanf("%d %d", &n1, &n2);

    for(i=1; i <= n1 && i <= n2; ++i)
    {
        
        if(n1%i==0 && n2%i==0)
            gcd = i;
    }

    printf("G.C.D of %d and %d is %d", n1, n2, gcd);

    return 0;
}

and

print

15 : 15, 30, 45, 60, 75, 90, 105, 120, 135, ...

20 : 20, 40, 60, 80, 100, 120, 140, ...

Common Multiple = 60, 120, ...

inside

#include <stdio.h>

int main() {

    int n1, n2, max;

    printf("Enter two integers: ");
    scanf("%d %d", &n1, &n2);

    max = (n1 > n2) ? n1 : n2;

    while (1) {
        if ((max % n1 == 0) && (max % n2 == 0)) {
            printf("The LCM of %d and %d is %d.", n1, n2, max);
            break;
        }
        ++max;
    }
    return 0;
}

sl0th
  • 1
  • 6
    Read up on the Euclidean Algorithm. It's much better than your brute-force GCD calculation. – paddy Oct 26 '22 at 04:49
  • 1
    Check Wikipedia on [Greatest Common Divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). Euclid's algorithm is the oldest algorithm. – Jonathan Leffler Oct 26 '22 at 05:20
  • 1
    I agree that euclid's division is much more efficient algorithm. But if you want an example of getting prime factorisation, then I already have made a header file - https://github.com/lakshayrohila/getprimefactorisation.h . Take a look at its content to get an idea of how to get prime factorisation of a number. Both the HCF and LCM can be gotten using the prime factorisation, the way we are taught in smaller classes in schools. – L_R Oct 26 '22 at 05:24
  • This answers your first question: https://stackoverflow.com/a/40273702/4386427 – Support Ukraine Oct 26 '22 at 05:46

0 Answers0