Quant, Math & Computer Science Puzzles for Interview Preparation & Brain Teasing A collection of ~225 Puzzles with Solutions (classified by difficulty and topic)

Subscribe to this blog

Follow by Email!

Comparison without relational operators

Get link

Facebook

Twitter

Pinterest

Google+

Email

Other Apps

Source: Quant interview at Religare Technova

Problem: Write a C program to compare two integers without using relational operators (== != < <= > >=)

say 2 nos are a and b in their n-bit representations. subtract b from a by taking 2's complement of b and adding it to a, multiply it by 100...(n-1 0s). then right-shift the no n-1 times. call it c. multiply c by b. then complement c, multiply it by a. now max = b*c+a*(complement of c)

int d = a - b;

ReplyDeleteif(d)

{

// a is not equal to b

if( d - abs(d) )

{

// d was negative => b > a

}

else

{

// d was positive => a > b

}

}

else

{

// a == b :)

}

In the implementation of abs(), a relational operator is used to determine whether the number passed is less than or greater than zero.

Deletesay 2 nos are a and b in their n-bit representations. subtract b from a by taking 2's complement of b and adding it to a, multiply it by 100...(n-1 0s). then right-shift the no n-1 times. call it c. multiply c by b. then complement c, multiply it by a. now max = b*c+a*(complement of c)

ReplyDeleteWill this work?

ReplyDeleteint compare(int64_t a, int64_t b)

{

return ((uint64_t) (a - b)) >> 63;

}

Sorry but i couldn't make it simpler..

ReplyDelete#include

#include

int maximum(int x,int y)

{

return(x+y+sqrt(-2*y*x +x*x + y*y))/2;

}

int main()

{

int a,b,c;

scanf("%d%d",&a,&b);

c=maximum(a,b);

printf("\n%d",c);

}

int main () {

ReplyDeleteint a,b;

printf ( "enter the two values u like to compare\n");

scanf (" %d %d",&a,&b);

if (!(a ^ b))

printf ("both are equal\n);

else

printf ("both are not equal\n");

}

int ret_max(int a, int b){

ReplyDeleteint c=a,d=b;

while (c&d){

c&=(c-1);

c&=(d-1);

}

if (c)

return a;

else // also takes care of equality

return b;

}

//to check if no's are equal

ReplyDeleteif(!(a^b))

print(equal)

else if (a/b)

print(b greater than a)

else

print(a greater than b)