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?)
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.
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...
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With