Convert recursive function to a loop (ternary operator)

219 Views Asked by At

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

There are 1 best solutions below

0
On BEST ANSWER

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;
}