Home
Questions
Search
Forum
Contact
Guest Book
Polls!
Got a Question?
 
PREV
Programs
NEXT
 
(50 / 301)
 
 



Write a C program to find the GCD of two numbers.




Here is a C program ....


#include <stdio.h>

int gcd(int a, int b);
int gcd_recurse(int a, int b);


int main()
{
  printf("\nGCD(%2d,%2d) = [%d]", 6,4,  gcd(6,4));
  printf("\nGCD(%2d,%2d) = [%d]", 4,6,  gcd(4,6));
  printf("\nGCD(%2d,%2d) = [%d]", 3,17, gcd(3,17));
  printf("\nGCD(%2d,%2d) = [%d]", 17,3, gcd(17,3));
  printf("\nGCD(%2d,%2d) = [%d]", 1,6,  gcd(1,6));
  printf("\nGCD(%2d,%2d) = [%d]", 10,1, gcd(10,1));
  printf("\nGCD(%2d,%2d) = [%d]", 10,6, gcd(10,6));

  printf("\nGCD(%2d,%2d) = [%d]", 6,4,  gcd_recurse(6,4));
  printf("\nGCD(%2d,%2d) = [%d]", 4,6,  gcd_recurse(4,6));
  printf("\nGCD(%2d,%2d) = [%d]", 3,17, gcd_recurse(3,17));
  printf("\nGCD(%2d,%2d) = [%d]", 17,3, gcd_recurse(17,3));
  printf("\nGCD(%2d,%2d) = [%d]", 1,6,  gcd_recurse(1,6));
  printf("\nGCD(%2d,%2d) = [%d]", 10,1, gcd_recurse(10,1));
  printf("\nGCD(%2d,%2d) = [%d]", 10,6, gcd_recurse(10,6));
  

  getch();
  getch();
  return(0);
}

// Iterative algorithm
int gcd(int a, int b)
{
   int temp;
   
   while(b)
   {
      temp = a % b; 
      a = b; 
      b = temp;
   }

   return(a);
}


// Recursive algorithm
int gcd_recurse(int a, int b)
{
   int temp;

   temp = a % b;

   if (temp == 0)
   {
      return(b);
   }
   else
   {
      return(gcd_recurse(b, temp));
   }
}




And here is the output ...


Iterative
----------------
GCD( 6, 4) = [2]
GCD( 4, 6) = [2]
GCD( 3,17) = [1]
GCD(17, 3) = [1]
GCD( 1, 6) = [1]
GCD(10, 1) = [1]
GCD(10, 6) = [2]

Recursive
----------------
GCD( 6, 4) = [2]
GCD( 4, 6) = [2]
GCD( 3,17) = [1]
GCD(17, 3) = [1]
GCD( 1, 6) = [1]
GCD(10, 1) = [1]
GCD(10, 6) = [2]


Note that you should add error handling to check if someone has passed negative numbers and zero.


PREV
COMMENTS                                  INDEX                                  PRINT
NEXT



Last updated: November 3, 2005

www.cracktheinterview.com - Your destination for the most common IT interview questions, answers, frequently asked interview questions (FAQ), C Programs, C Datastructures for technical interviews conducted by the top IT companies around the world!