Question: This is done in C language 1. What does this mystery function do? For what values of x does it return true? Can you explain

This is done in C language

1. What does this mystery function do? For what values of x does it return true? Can you explain why?

#define mystery(x) ((((x) - 1) & (x)) == 0)

2. Imagine we want to write a function that finds the middle point of two integers. If their sum is odd, the function should either round down or up.

int midpoint_bad(int x, int y) { return (x + y) / 2; }

As the name of the function suggests, this is not a good implementation. Can you find an example (values for x and y) where the above function returns an incorrect value? Please show your x, y and the value returned by C when the above function is called.

How about this? Is this correct?

int midpoint_better(int x, int y) { return x + ((y - x) / 2); }

3) This last one is the best implementation for this function. It is given by one of the greatest computer scientists of all time, Donald Knuth, in his very famous book, The Art of Computer Programming:

int midpoint_knuth(int x, int y) { return (x & y) + ((x ^ y) >> 1); }

Choose random values of X and Y and show how the above returns the correct midpoint. Does it work if X, Y or both are negative?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!