IP-15.c (1035B)
1 /* Write a program to calculate the GCD of two numbers 2 (i) using recursion 3 (ii) without recursion 4 */ 5 6 #include <stdio.h> 7 8 int gcd_tail_rec(int, int); 9 int gcd_rec(int, int); 10 int gcd_ite(int, int); 11 12 int main() 13 { 14 int a, b; 15 printf("Enter two number: "); 16 scanf("%d %d", &a, &b); 17 if (a < 0) 18 a = -a; 19 if (b < 0) 20 b = -b; 21 printf("\nGCD (Tail-Recursion) of %d and %d is = %d", a, b, gcd_tail_rec(a, b)); 22 printf("\nGCD (Recursion) of %d and %d is = %d", a, b, gcd_rec(a, b)); 23 printf("\nGCD (Iteration) of %d and %d is = %d", a, b, gcd_ite(a, b)); 24 return 0; 25 } 26 27 int gcd_tail_rec(int a, int b) 28 { 29 if (b == 0) 30 { 31 return a; 32 } 33 else 34 { 35 return gcd_tail_rec(b, a % b); 36 } 37 } 38 39 int gcd_rec(int a, int b) 40 { 41 if (b == 0) 42 { 43 return a; 44 } 45 else 46 { 47 return gcd_rec(b, a % b); 48 } 49 } 50 51 int gcd_ite(int a, int b) 52 { 53 int temp; 54 while (b > 0) 55 { 56 temp = b; 57 b = a % b; 58 a = temp; 59 } 60 return a; 61 }