You are invited to Log in or Register a free Frihost Account!

# a small algorithmic problem.

akshar
can some one tell me how i can find maximum of two given integers without using decision or looping constructs?
shamil
 akshar wrote: can some one tell me how i can find maximum of two given integers without using decision or looping constructs?

What do you mean?
raver
no i don`t think you can...to calculate something you need to have atleast one decisional structure... i had this problem at a mid-term exam this winter in basic programming ...it would be something like:

 Code: #include using namespace std; int main() { int a, b; cout<< "Insert 2 numbers and i`ll find out which is the largest"<>a>>b; if(a>b) { cout<a) { cout<<"b >>" is bigger then "<

this would be in c++ ...if you want i can make a version in php although it is pretty simple.
mathiaus
use the max!
http://uk.php.net/max

 Code:

that would echo 7

to findsomething in php search google. inlcude in the search bar the word 'php' and then explain what you want. usually comes up with good results
kv
Possible

assuming \$a and \$b are two integers

 Code: floor(\$a/\$b) * \$b + (\$a % \$b)

will return the biggest of them. Note that in the above code, \$a and \$b are interchangeable.

That is php code. But I guess it gives an idea.
dandelion
Well, he has not asked for code, but algorithm.

I think, the best one is based on comparison.

Is A greater than B?
YES: MAX is A and A is MAX.
NO: MAX is B and B is MAX.

The algorithm can be realized with:

1) the if/else control structure supported by almost all languages
 Code: if (a > b) { max = a } else { max = b }

2) trinary operator (if any supported by the given language)
 Code: max = a > b ? a : b

3) the max() function supported by some languages
 Code: max = max(a, b)
yzy
I DON'T KNOW WHAT YOU MEAN.
Sappho
 yzy wrote: I DON'T KNOW WHAT YOU MEAN.

Simple he meant how to get the max from 2 integer numbers without comparison, so the only good answer was from kv others just used decision (good old ifs) or functions based on decision like max(a,b).
akshar
max=(a+b +abs(a-b))/2
shabda