Thursday, 15 August 2013

chapter 5 Solutions Problem [J][k]

Question-Write a function to compute the greatest common divisor 
given by Euclid’s algorithm, exemplified for J = 1980, K =
1617 as follows: 
1980/ 1617 = 1 
1980– 1* 1617 = 363 
1617/ 363 = 4  1617– 4* 363= 165 
363 / 165= 2  363 – 2 * 165= 33 
5 / 33= 5  165 – 5 * 33 = 0 
Thus, the greatest common divisor is 33. 

Happy Independence day to all my Indian viewers. 
this is really fundamental and method of finding HCF is very effective but problem is that it's really hectic to generalize this for 3 and more numbers. so here is the solution for 2 number problem.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int a,b;
printf("Enter any 2 numbers\n");
scanf("%d%d",&a,&b);
hcf(a,b);
getch();
}
hcf(int a,int b)
{
int j;
while(b!=0)
{
    j=a%b;  /* you can easily notice that difference calculated  is nothing but a%b*/
    a=b;
    b=j;
if(b==0)
break;
}
printf("Highest common divisor=%d\n",a);
}






No comments:

Post a Comment