Thursday 14 March 2013

Write a program to find the G.C.D of two numbers.

Statement:
Write a program to find the GCD of two numbers.



 Algorithm:

            Step-1: Read two numbers a,b
            Step-2: if (a>b)
                        Max=a, Min=b
            Step-3: Else,
                Max=b, Min=a
            Step-4: c=Max%Min
            Step-5: while(c!=0)
                       1.    Max=Min
                       2.    Min=c
                       3.    C=Max%Min
            Step-6: Print Min (GCD)
            Step-7: End
   


Program Listing:

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c,max,min;
printf("Enter the two numbers:");
scanf("%d%d",&a,&b);
if(a>b)
{
max=a;
min=b;
}
else
{
max=b;
min=a;
}
c=max%min;
while(c!=0)
{
max=min;
min=c;
c=max%min;
}
printf("The GCD of given two numbers is=%d", min);
getch();
}



Output:
Enter the two numbers: 56
42
The GCD of given two numbers is= 14


Discussion:
I.    It works properly.
II.    The GCD can be made fo more than two numbers.
III.    Since we use short signed int so it works within the number range  -32768  to +32767
IV.    If we use long int then it works within the number range  -2147483648  to  +2147483647

1 comment: