0

so I have this code from an exam question and I have to convert the recursive part with a loop, now I tried many times but the loop will be endless, here what I did:

code with recursive

int f(int n, int m) { int k; if (m == 0) return n; k = n % m; return k==0 ? m : f(m,k); } 

code with loop

 int ff(int n, int m) { int k; if (m == 0) return n; k = n % m; if (k == 0 ) return m; else { for(int i = 0 ; k != 0; i++ ) { int h; h = k % m; if( h == 0 ) return k; } } return m; } 
1
  • 1
    Please do some rubber duck debugging of that loop. (Hint: When and where do you modify k or m?) Commented Jul 12, 2020 at 10:55

1 Answer 1

1

A non-recursive function can look for example the following way

int f( int n, int m ) { if ( m ) { while ( n % m ) { int tmp = m; m = n % m; n = tmp; } } return m ? m : n; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.