'GCD function for 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?)
Solution 1:[1]
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;
}
Solution 2:[2]
This problem can also be solved in a very clean way with recursion:
int gcd(int a, int b) {
int remainder = a % b;
if (remainder == 0) {
return b;
}
return gcd(b, remainder);
}
Solution 3:[3]
I executed this statements for GCD :
#include<stdio.h>
#include<conio.h>
int main(){
int l, s,r;
printf("\n\tEnter value : ");
scanf("%d %d",&l,&s);
while(l%s!=0){
r=l%s;
l=s;
s=r;
}
printf("\n\tGCD = %d",s);
getch();
}
Solution 4:[4]
The GCD computation in C :
int gcd(int a, int b){
if (a && b) for(;(a %= b) && (b %= a););
return a | b;
}
The absolute value computation :
#include <limits.h>
unsigned int abso(int v){
const int mask = v >> (sizeof(int) * CHAR_BIT - 1);
return (v + mask) ^ mask;
}
Solution 5:[5]
Using a bit of recursion and Objective-C
-(int)euclid:(int)numA numB:(int)numB
{
if (numB == 0)
return numA;
else
return ([self euclid:numB numB:numA % numB]);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Omar Faruk |
Solution 4 | |
Solution 5 | Trygve |