Search code examples
clinuxbinaryinfinite-loopfractions

Infinite loop when simplifying fractions in binary in C


I'm trying to simplify fractions in binary with this code that checks if the value is even:

int is_even(floatlet value){
  if(value & 1) return 0;
  return 1;
}

And this while loop keeps bit shifting until the value is odd.

while(is_even(numerator) && is_even(denomExp)){
  numerator >>= 1;
  denomExp <<= 1;
}

The while loop goes on an infinite loop. I'm wondering why? We've done test and the is_even function works fine. Thanks!


Solution

  • Your loop is incorrect: you should be shifting demonExp to the right too. It runs indefinitely for numerator=0 and an even denomExp.

    If numerator and denomExp are integer types, and the number is just a fraction numerator/denomExp, you can fix the code this way:

    while (numerator && is_even(numerator) && is_even(denomExp)) {
        numerator >>= 1;
        denomExp >>= 1;
    }
    

    Conversely, if denomExp is the power of 2 by which to divide the numerator, you should increment it instead, and maybe test for overflow:

    while (numerator && is_even(numerator)) {
        numerator >>= 1;
        denomExp += 1;
    }
    

    You must post the type definition and semantics as well as the complete code in question.