Find K such that |A – K| = |B – K|
Last Updated :
07 Mar, 2022
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.
Examples:
Input: A = 2, B = 16
Output: 9
|2 – 9| = |16 – 9| = 7
Input: A = 5, B = 2
Output: -1
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:
C++
#include <bits/stdc++.h>
using namespace std;
int find_k( int a, int b)
{
if ((a + b) % 2 == 0)
return ((a + b) / 2);
return -1;
}
int main()
{
int a = 2, b = 16;
cout << find_k(a, b);
return 0;
}
|
Java
class GFG
{
static int find_k( int a, int b)
{
if ((a + b) % 2 == 0 )
return ((a + b) / 2 );
return - 1 ;
}
public static void main(String[] args)
{
int a = 2 , b = 16 ;
System.out.println(find_k(a, b));
}
}
|
Python3
def find_k(a, b) :
if ((a + b) % 2 = = 0 ) :
return ((a + b) / / 2 );
return - 1 ;
if __name__ = = "__main__" :
a = 2 ; b = 16 ;
print (find_k(a, b));
|
C#
using System;
class GFG
{
static int find_k( int a, int b)
{
if ((a + b) % 2 == 0)
return ((a + b) / 2);
return -1;
}
public static void Main()
{
int a = 2, b = 16;
Console.Write(find_k(a, b));
}
}
|
Javascript
<script>
function find_k(a, b)
{
if ((a + b) % 2 == 0)
return ((a + b) / 2);
return -1;
}
var a = 2, b = 16;
document.write( find_k(a, b));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...