Given two integers A and B where (A ≠ B). The task is to find K such that |A – K| = |B – K|. If no such K exists then print -1.
Input: A = 2, B = 16
|2 – 9| = |16 – 9| = 7
Input: A = 5, B = 2
Approach: It is given that A ≠ B. So let A < B then there are three cases:
- K < A: This gives A – K = B – K which gives A = B which is false.
- K > B: This gives K – A = K – B which is also false.
- A ≤ K ≤ B: This gives K – A = B – K which gives 2 * K = A + B
If A + B is odd, there is thus no solution. If A + B is even then the answer is (A + B) / 2.
Below is the implementation of the above approach:
- Program to find whether a no is power of two
- Program to find parity
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Find Union and Intersection of two unsorted arrays
- To find sum of two numbers without using any operator
- Find day of the week for a given date
- Given a number, find the next smallest palindrome
- Find the element that appears once
- Find the largest multiple of 2, 3 and 5
- Program to find amount of water in a given glass
- Find the maximum distance covered using n bikes
- Find if two rectangles overlap
- Find the smallest number whose digits multiply to a given number n
- Find next greater number with same set of digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.