Page 1 of 1

#1 Tiny coding teaser

Posted: Tue Oct 30, 2007 11:00 am
by Ace Pace
int f(int x) { (x!=0) ? (return X&1+f(x>>1)) : (return 0) }
int main
{
int a=?
f(x );
}

Part 1:
What does int f(x) do?


Part 2: Using the following stack trace, can you conclusively tell if a was a number greater then 30?
Image
EDIT: I fucked up the stack trace, that should be 12, nor 16. I screwed up my math and i'm too tired to fix the image

Note: The left side is adresses randomly chosen, as is the longer hex data fragment on the right.
This contains all the data you need.
Oh, right, the data fragment is in hex, answer me in decimal.

#2

Posted: Tue Oct 30, 2007 11:57 am
by Destructionator XV
The program counts the set bits in the number given. What it does is check the one on the right, adding 1 to the total if it is 1, 0 if it is 0, then shifts it all right one slot and does it again, repeating until there is nothing left.

The stack trace has repeating sets of two values: the function's argument, and the place in memory to go back to when it is done. It goes from bottom up in the picture.

Notice the one number being sliced in half each time - what is what shifting all the bits to the right does. That is the function argument. The other number up there is the place to return to when the function is done. Notice the same value is repeated there - this tells us that we are currently in the middle of the process, since that signifies it is doing the same thing over and over again.

Since we are somewhere in the middle, the first number would be 2 * the biggest number we see (0x12 which is 18 decimal times 2 is 36.) 36 > 30, so that answers part b.

We don't see the whole thing here, so the first number isn't necessarily 36, but we do know it is at least that big.