Hi everyone
I have to write a c program that calculates the greatest common divisor of two positive numbers , using the euclides algorithm . I have to implement two functions , one that works recursively to find the gdc and one that works with WHILE .
The main has to call both functions and print the gcd found by each one PLUS how many steps each function needed to complete the task . By steps , i mean how many times the recursive function was called in the first function
and how many times the WHILE looped in the second function
Here is my solution . I would really appreciate any corrections or tips
Thanks in advance
Code:#include <stdlib.h> int gcdrecurs(int m,int n,int *steps1 ) { int temp , r ; *steps1 = *steps1 + 1; r = m % n; if (r == 0) { return n; } else { return gdcrecurs(n , r , steps1 ); } } int gdcwhile(int m , int n , int *steps2) { int temp ; *steps2 = 0 ; while (n !=0 ) { *steps2 = *steps2 + 1 ; temp = m ; m = n ; n = temp % n ; } return m; } main() { int a1 , a2 , temp , gdc1 , gdc2 , steps1 , steps2 ; printf("type two positive numbers\n"); scanf("%d",&a1); scanf("%d",&a2) if (a1 < a2) { temp = a1; a1 = a2; a2 = temp ; } steps1 = 0; gdc1 = gcdrecurs(a1,a2,steps1); printf("the gdc is %d and %d steps were needed using recursion" ,gdc1,steps1); gdc2 = gdcwhile(a1,a2,steps2); printf("the gdc is %d and %d steps were needed using while loop",gdc,steps2); return 0; }



LinkBack URL
About LinkBacks



)