Find the Values of X and Y
Find the Values of X and Y
Observe the values of X and Y in the Given Equations
Given two numbersand
. Find the values of
X
and
Y
in the equations.
- A = X + Y
- B = X xor Y
The
chore
is to brand Ten equally minimum as possible. If it is non possible to observe any valid values for X and Y then print -i.
Examples:
Input : A = 12, B = 8 Output : X = 2, Y = x Input : A = 12, B = 9 Output : -1
Let’s take a look at some bit in X, which is equal to 1. If the corresponding fleck in Y is equal to 0, then ane can swap these two $.25, thus reducing 10 and increasing Y without changing their sum and xor. Nosotros can conclude that if some bit in 10 is equal to 1 then the corresponding flake in Y is also equal to ane. Thus, Y = 10 + B. Taking into business relationship that X + Y = 10 + Ten + B = A, one can obtain the following formulas for finding X and Y:
- X = (A – B) / ii
- Y = X + B = (A + B) / 2
Ane should also detect that if
A < B
or A and B have unlike parity, so the answer doesn’t exist and output is -1. If Ten and (A – 10) not equal to X then the answer is also -one.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using
namespace
std;
void
findValues(
int
a,
int
b)
{
if
((a - b) % ii == ane) {
cout <<
"-one"
;
return
;
}
cout << (a - b) / 2 <<
" "
<< (a + b) / 2;
}
int
main()
{
int
a = 12, b = eight;
findValues(a, b);
return
0;
}
Java
import
java.io.*;
class
GFG
{
static
void
findValues(
int
a,
int
b)
{
if
((a - b) %
two
==
1
)
{
System.out.println (
"-one"
);
return
;
}
Arrangement.out.println (((a - b) /
2
)+
" "
+
((a + b) /
2
));
}
public
static
void
principal (String[] args)
{
int
a =
12
, b =
8
;
findValues(a, b);
}
}
Python3
def
findValues(a, b):
if
((a
-
b)
%
two
=
=
ane
):
print
(
"-1"
);
return
;
impress
((a
-
b)
/
/
ii
, (a
+
b)
/
/
2
);
a
=
12
; b
=
8
;
findValues(a, b);
C#
using
System;
class
GFG
{
static
void
findValues(
int
a,
int
b)
{
if
((a - b) % 2 == i)
{
Console.Write (
"-1"
);
return
;
}
Console.WriteLine(((a - b) / 2)+
" "
+
((a + b) / 2));
}
static
public
void
Principal ()
{
int
a = 12, b = eight;
findValues(a, b);
}
}
PHP
<?php
function
findValues(
$a
,
$b
)
{
if
((
$a
-
$b
) % ii == 1)
{
echo
"-1"
;
return
;
}
echo
(
$a
-
$b
) / 2,
" "
,
(
$a
+
$b
) / 2;
}
$a
= 12;
$b
= 8;
findValues(
$a
,
$b
);
?>
Javascript
<script>
function
findValues(a, b)
{
if
((a - b) % 2 == i)
{
document.write(
"-i"
);
return
;
}
document.write( (a - b) / 2+
" "
+
(a + b) / 2);
}
let a = 12;
let b = 8;
findValues(a, b);
</script>
Fourth dimension Complexity: O(1), since there is only bones arithmetic that takes constant fourth dimension.
Auxiliary Infinite: O(1), since no extra space has been taken.
Find the Values of X and Y
Source: https://www.geeksforgeeks.org/find-the-values-of-x-and-y-in-the-given-equations/