stuck in GCD of 2 numbers in C using recursion -
i getting segmentation fault following program. trying find out gcd using recursive function. code is:
#include<stdio.h> int gcd(int a, int b) { int temp, g, c; if(a>b) { c=a; a=b; b=c; } //printf("the values of , b are: %d %d",a,b); temp = % b; if(temp != 0) { g = gcd(b, temp); return(g); } if(temp == 0) g= b; return g; } int main() { int a,b; printf("enter 2 numbers: \n"); scanf("%d %d", &a, &b); printf("the gcd of 2 numbers entered are: %d\n", gcd(a,b)); } the problem found out in swapping variables. if removing code working fine. can tell me going wrong? trying implement using euclidean algorithm. no other method can implemented.
if(a>b) { c=a; a=b; b=c; } temp = % b; the problem here. first, you're making sure b > a. now, if b greater a, it's not difficult prove a % b == a. instance, 2 % 5 = 2.
just replace last line
temp = b % a; or, better, reverse condition swapping :
if(a < b)
Comments
Post a Comment