Welcome to MindCipher, a social repository of the world's greatest brain teasers, logic puzzles and mental challenges.

No if() Only abs()

Given two variable a and b, construct a function f(a,b) which return the maximum one in {a,b}.

You can only use +- · / and abs() (to take the absolute value). NO if() is allowed in your construction.

Pure arithmetic ; )

{a+b+abs(a-b)}/2

Also, {a+b-abs(a-b)}/2 is the smaller one in {a,b}

Comments


sincerekamal

sure it would b wrong...but i tried something...

int res=(a-b)>0?a:b;

it too doesn't have if()

  

Aakash

That's a good point, but I think the idea is to avoid conditionals altogether. Your compiler turns the ternary ( ? : ) operator into the same code that it turns an if statement into (i.e. a conditional branch with two blocks).


Valentin

Great question! Thoroughly enjoyed thinking about this one.


Wyverald

You didn't say you could use a 2 in there.

So you'll need to make one with (a/a + b/b) or something like that.

  

Ravi

That's a good point. More verbosely, {a+b+abs(a-b)} / [{a+b+abs(a-b)}+{a+b+abs(a-b)}]

  

MoralMachine

Good point. Nod. But we have to exclude 0.

Whatever, the question should just emphasize on "pure arithmetic" or ask for an algebra expression.


Valentin

Or: {a + b + abs(a-b)}/(a/a + a/a). Slightly shorter version.

  

Valentin

This, however, of course wouldn't work if a was 0. So perhaps the parent's reply is actually more general.

  

Valentin

Jeez, I'm going in circles here. ravi's reply is incorrect. That whole expression simply equals 1/2. As long as a and b are not both equal to 0, the following would suffice: {a + b + abs(a-b)}/{(a + a + b + b)/(a+b)}

  

Aakash

Agreed, unless both a and b are zero...


Jay Elliott

Isn't that just 1/2?


Oliver Matthews

Thinking about this, I'm fairly sure it is impossible unless you do one of the following: 1. allow numbers in the algorithm (as per solution) 2. assume at least one of the values is not 0. (as per below) 3. allow ^ 4. use a system that defines 0/0 as 1 (i.e. is wrong).

the last two would allow you to implicitly get a 1 by doing (a^a)/(a^a) or a/a respectively (and thus a 2 through addition).


Grant Goodman

Here's an intuitive derivation of the solution:

(a+b)/2 gives you the average, which is directly in between a and b, and it is 1/2 the difference from either a or b. So to get to the larger one, just add the difference of the two divided by two, giving you (a+b)/2 + abs(a-b)/2, or (a+b+abs(a-b))/2

  

Ravi

That's an awesome explanation. MoralMachine, I suggest adding it to the puzzle solution.

Check out other puzzles:
Random  

Like this? You might also like:
Clever Commuter
Burning Rope
Partitioning a set
Submitted by
MoralMachine
3 months ago
Likes
Difficulty 5.4 ?

Tags
None

Back