15

I just came across this piece of recursive code, as much as I can guess this should be an infinite recursion but somehow it executes and does terminate. Can anybody tell me how this happens and what will be it's time complexity ?

Comments
  • 17
    Integer overflow
  • 1
    I guess it somehow uses the overflow in the integer to terminate the recursion, not sure. Is the complexity going to be infinite ?
  • 11
    It's complexity is undefined, exactly as the behaviour of this shit code.
  • 4
    You have the code, print n before you call yourself. Don’t guess, debug.
  • 3
    @RantSomeWhere @nitwhiz it is a bad piece of code but somehow this was given in one of our university exams. I guess they just wanted the students to point out the error.
  • 3
    @gdsoumya so it’s your homework.
  • 2
    @broseph not at all. This was in a previous year question paper.
  • 5
    This code could terminate, not terminate or do anything because signed integer overflow is undefined behaviour in C / C++.
  • 1
    @RantSomeWhere u don't need an else block because only one of the returns should technically work so this is equivalent to a code with else block.
  • 2
    Why dont you use -o?
  • 2
    @HampusMa I didn't require a custom executable file, a.out was good enough in this case.
  • 2
    @gdsoumya okay. I personally find it more efficient with -o but it's personal preference.
  • 3
    Just as an aside

    Even though you guys are correct in saying that integer overflow is not defined everything that happens can be easily explained

    If you take the time to make an equation the value you are looking for becomes 2^n*99+1 mod 2^32=1

    99 has no common divider with 2 so n>=32 and who could have guessed the 32nd value is a one

    So even though the compiler is allowed to do whatever there is not much optimization going on it seems and it works out to be O(32) on your machine at least.
  • 1
    Integer overflow at its finest
  • 1
    Pretty clear how the recursion is ending, but still pretty cool!
Add Comment