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
int gcd(i
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);
}
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]);
}
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();
}
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;
}