Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this code work to find the largest of three numbers without using any comparison operator?

Tags:

algorithm

Here is the function that finds the greater of two numbers:

int larger(int a,int b)
{
    int c=a-b;
    int k=c>>31&1;
    int max=a-k*c;
    return max;
 }

To find the greatest of three numbers, call it such as:

larger(a,larger(b,c));

How does this work?

like image 661
Eight Avatar asked Nov 27 '11 06:11

Eight


People also ask

How do you write a program to find the greatest of 3 numbers?

The steps followed in this program are: The program store these numbers into three variables num1 , num2 and num3 using scanf() function. 2. Program compares num1 to other two variables num2 & num3 and if num1 is grater than both of these numbers then print num1 is the largest number. 3.

How do you find the largest of 3 numbers in Python?

Using max() function to find the greatest number max(lst).


2 Answers

int c=a-b;

cwill be negative if a < b else it will positive. Now a negative number will have its most significant bit(MSB) set.

int k=c>>31&1;

This step assumes that sizeof(int) is 4 bytes and extracts the MSB of c in k. So k is either 0 or 1

int max=a-k*c;

replacing c = a-b in this we get max = a-k*(a-b). So when

k = 0, max = a-0*(a-b)
           = a

k = 1, max = a-1*(a-b)
           = b
like image 79
codaddict Avatar answered Sep 18 '22 12:09

codaddict


This only works for 32-bit integers, of course.

k=c>>31&1 isolates the sign bit, which is 0 or 1.

If k is 0, then a>=b and max = a - 0*(a-b) = a.

If k is 1, then a<b and max = a - 1*(a-b) = a-a+b = b.

Historically, instruction pipelining was the main reason for using code that avoids an if test. If the pipeline is deep and the processor doesn't use branch prediction, a half-dozen integer operations can take less time to do than the time lost due to pipeline refilling and dealing with speculative stores, if any. With branch prediction, code with an if (or equivalent) might be faster. Either way, the cost of the nanoseconds saved or lost might never exceed the program-maintainance costs for that code.

like image 37
James Waldby - jwpat7 Avatar answered Sep 19 '22 12:09

James Waldby - jwpat7