Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Spatial Database Systems Design Implementation And Project Management

Authors: Albert K.W. Yeung, G. Brent Hall

1st Edition

1402053932, 978-1402053931

More Books

Students also viewed these Databases questions