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
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;
}
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.
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.
@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.
âThis is not dependent on the sign of the numbers as @cyberax pointed out.â
true ! my bad. i was tired
Thanks, it helped me to understand the concept.!
can anyone tell me s for what? I can not understand. is it third number of three numbers? or it means any constant value? please explain
abs() is a function
#include<studio.h>
int main()
{
int a,b;
printf(âEnter two no.â);
scanf("%d %d",&a,&b);
if(a>b)
printf(âgreater is %dâ,a);
else
printf(âgreater is %dâ,b);
return 0;
}
By considering cases a>b
and aâ¤b, itâs easy to see that
|aâb|=max(a,b)âmin(a,b),(note:|aâb|=|bâa|)
and
a+b=max(a,b)+min(a,b).
now put value of min(a,b) from above