I want to swap two variables with only +=
and -=
operators and without temporary variables. I know the standard solutions like:
a = a+b;
b = a-b;
a = a-b;
and with xor
:
a ^= b;
b ^= a;
a ^= b;
but I cannot figure out how to do it with only +=
and -=
. Is it possible?
Example: Suppose, there are two numbers 25 and 23. X= 25 (First number), Y= 23 (second number) Swapping Logic: X = X + Y = 25 +23 = 48 Y = X - Y = 48 - 23 = 25 X = X -Y = 48 - 25 = 23 and the numbers are swapped as X =23 and Y =25.
Given two variables, x, and y, swap two variables without using a third variable. The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.
Using arithmetic operators Swapping two variables without using a third variable. The arithmetic operators for addition and subtraction can be used to perform the swap without using a third variable. Similarly, multiplication and division can be used to perform the swap without using the third variable.
my classmates offer a nice solution:
the answer is NO
lets denote a
as (1 0)
and b
as (0 1)
the matrix A
is
1 0
0 1
+=
and -=
mean adding or subtracting lines to each other. That means the determinant either does not change its sign or it is equal to 0
. The end matrix is
0 1
1 0
with determinant equal to -1
, so you can not get it
UPDATE: you have these operations:
a-=a
. One line becomes 0
, so det=0
a+=a
. That means multiplying a line by 2
, so the det A'= 2*det A
a+=b
. That means elementary transformation, which does not change the value of det
a-=b
. The same thing as with 3.
Then apply this proof for b-=b
, b+=b
, b+=a
, b-=a
. So the determinant does not change its sign or it is 0
UPDATE 2:
as @Tom said here is the example of how to do that in C#: http://ideone.com/UzVLML. However, in C thats not correct: http://codepad.org/Rmhn9iqb. Can someone clarify the difference of b -= b += b
in C and C#?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With