How To Find Max Of 3 Numbers Without Using Comparison Operators?

in c++ create a vector<int>, sort it, then print the 3d number. Otherwise I have no clue how to do it without comparison operator.

vector<int> array;
array.resize(3);
// populate the array with 3 random values
array[0] = rand();
array[1] = rand();
array[3] = rand();
// sort
sort(array.begin(),array.end());
// display the largest number
cout << array[2] << endl;

Or Something like this

int a=rand();
int b=rand();
int c=rand();
std::vector<int> vec;
vec.push_back(a);
vec.push_back(b);
vec.push_back(c);
std::cout<< *std::max_element(vec.begin(),vec.end())<<std::endl;

All these methods just call procedures that use the comparison operators.

All these methods just call procedures that use the comparison operators.

Then why don't you suggest another way. :D

>Then why don't you suggest another way.
How about you figure it out instead of encouraging people to do the OP's homework.

Then why don't you suggest another way. :D

How about this? Although it uses equality, which is technically a comparison operator. "Is i1 greater than i2?"

bool greaterThan(const int& i1, const int& i2)
{    return ( ((i2-i1)==abs(i2-i1)) ? false:true );    }

How To Find Max Of 3 Numbers Without Using Comparison Operators?

Is that the exact and whole problem? Or did you paraphrase the problem? I don't believe there is a solution to the problem you posted if none of the solutions previously posted are not acceptable. If there is, I hope someone posts it :eek:

>If there is, I hope someone posts it
There is, but it's not entirely portable and it doesn't necessarily work for all cases. My guess is that the OP is paraphrasing, or the problem isn't designed for a thorough solution (aka. homework).

How about you figure it out instead of encouraging people to do the OP's homework.

I tried for two numbers but still it has problem which maybe you can rectify.

BIGGER=a-((a-b)&((a-b)>>(sizeof(int)*8-1)));

Problem Facing:(a-b) can overflow causing undefined behaviour. Eg: a = INT_MAX, b = -1.

simple arithmetic is all you need...
max(a,b) = ( a + b + abs ( a - b ) ) / 2
min(a,b) = ( a + b - abs ( a - b ) ) / 2

commented: great :) +1

Its no coding secret or something but a simple formula kind of thing here it is :

For two numbers:

max( a , b ) = ( a + b + abs( a - b ) ) / 2

For three numbers it is:

max( a , b , c ) = ( a + b + c * 2 + abs( a - b ) + abs( a + b - c * 2 + abs( a - b ) ) ) / 4

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.