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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started