Write a c program to find max of 2 numbers

,

write a c program to find max of two number and number taken from user
you can use only operators +,-,abs,division and number should be integer

1 Like

it’s easy. the max between A and B can be considered as the value
located at |A-B|/2 distance from the middle (A+B)/2, to the right.
thus, the formula is : (A+B+abs(A-B))/2. you only use +, -, abs and
division. it only works for non-negative integers, obviously.

int max(int A, int B)
{
    return (A + B + abs(A - B)) / 2;
}
2 Likes

the formula is perfect…!!
But can you just explain it in another simpler way…I am sort of not getting how that formula was derived.

1 Like

Let B be the max.

                            |A-B|/2
                               |
                         |-----------|
                         v           v
----------- A ---------------------- B --------------
                         ^
                         |
                       (A+B)/2

As you can see, the formula is reversible, meaning if A is the max, the expression remains :

* (A+B) / 2 = (B+A) / 2
* |A-B| / 2 = |B-A| / 2

Thus, max(A, B) = middle_position + gap_between_both / 2
= (A+B) / 2 + |A-B| / 2
= (A + B + abs(A - B)) / 2

Hope this helps. :slight_smile:

2 Likes

@cool_techie It is pretty simple to understand. It follows from the definition of abs.

if A=B 
	abs(A-B) = 0
	A+B+abs(A-B) = 2A
if A>B
	abs(A-B) = A-B
	A+B+abs(A-B) = 2A
if B>A
	abs(A-B) = B-A
	A+B+abs(A-B) = 2B

This is not dependent on the sign of the numbers as @cyberax pointed out. But yes it has troubles with overflow and underflow.

1 Like

“This is not dependent on the sign of the numbers as @cyberax pointed out.”
true ! my bad. i was tired :slight_smile:

Thanks, it helped me to understand the concept.!

1 Like