Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCD function for C

Tags:

c

Q 1. Problem 5 (evenly divisible) I tried the brute force method but it took time, so I referred few sites and found this code:

#include<stdio.h>
int gcd(int a, int b)
{
    while (b != 0)
    {
        a %= b;
        a ^= b;
        b ^= a;
        a ^= b;
    }

    return a;
}

int lcm(int a, int b)
{
    return a / gcd(a, b) * b;
}

int main()
{
    int res = 1;
    int i;
    for (i = 2; i <= 20; i++)
    {
        res = lcm(res, i);
    }

    printf("%d\n", res);
    return 0;
}

This is very simple but I don't understand how function "gcd" works; can somebody please help me understand the logic. (I know it returns the GCD of 2 numbers but why so many operations?)

like image 384
Faizaan Mohammed Avatar asked Nov 02 '13 04:11

Faizaan Mohammed


People also ask

Is there a GCD function in C?

The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder). There are many ways to find the greatest common divisor in C programming.

What is GCD and LCM in C?

GCD or HCF: Largest Integer that can divide both the numbers without any remainder or with 0 as remainder. Least Common Multiple(LCM): is the smallest positive integer that is perfectly divisible by the given integer values. C Programming Interview / Viva Q&A List http://technotip.com/6378/c-programmi...

What is GCD method?

The greatest common divisor (GCD) of two or more numbers is the greatest common factor number that divides them, exactly. It is also called the highest common factor (HCF). For example, the greatest common factor of 15 and 10 is 5, since both the numbers can be divided by 5. 15/5 = 3. 10/5 = 2.


1 Answers

To your second question: The GCD function uses Euclid's Algorithm. It computes A mod B, then swaps A and B with an XOR swap. A more readable version might look like this:

int gcd(int a, int b)
{
    int temp;
    while (b != 0)
    {
        temp = a % b;

        a = b;
        b = temp;
    }
    return a;
}
like image 114
Jack Avatar answered Oct 04 '22 00:10

Jack