FRIHOSTFORUMSFAQTOSBLOGSDIRECTORY
You are invited to Log in or Register a 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 <iostream>
using namespace std;
int main()
{
int a, b;
cout<< "Insert 2 numbers and i`ll find out which is the largest"<<endl;
cin>>a>>b;
if(a>b)
{
cout<<a<<" is bigger then "<<b;
}
else if (b>a)
{
cout<<"b >>" is bigger then "<<a;
}
else cout <<"The two numbers are equal";
return 0;
}




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:
<?php
max(7, 3);
?>

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 Wink
kv
Possible Smile

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. Laughing

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. Rolling Eyes
Sappho
yzy wrote:
I DON'T KNOW WHAT YOU MEAN. Rolling Eyes


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). Smile
akshar
max=(a+b +abs(a-b))/2
shabda
So why ask if you already know the answers. but that was surely a clever algo.
@mathius, though i am not sure php max should be using decesion constructs behind the scenes.
Sappho
shabda wrote:
So why ask if you already know the answers. but that was surely a clever algo.
@mathius, though i am not sure php max should be using decesion constructs behind the scenes.


I think it does couse few IFs are prolly faster than calculation.
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2007 Frihost, forums powered by phpBB.