-2

I took a job interview and the following algorithm was asked and I didn’t manage to find out it’s purpose.

int func(int a, int b)
{
    int c = b;
    while (c <= a)
        c <<= 1;
    int d = a;
    while (d >= b)
    {
        c >>= 1;
        if (c<= d)
            d -= c;
    }
    return d;
}
3
  • 1
    Welcome to SO. As the interview seems to be over now, did you try it in a debugger and check what happens? Of did you try it on paper with some random numbers as input? You should do this to find out what a function does.
    – Gerhardh
    Commented Aug 22, 2022 at 9:58
  • Seemingly, a < b returns a, a == b returns 0, a > b returns ? garbage. Commented Aug 22, 2022 at 10:06
  • If b == 0 and a >= 0 it is an infinite loop.
    – Computable
    Commented Aug 22, 2022 at 15:45

1 Answer 1

0

This function returns the modulo (a%b).

2
  • Only for positive values.
    – Gerhardh
    Commented Aug 22, 2022 at 10:17
  • Implementation defined behaviour shifting signed numbers. Commented Aug 22, 2022 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.