Reputation: 4510
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?
Upvotes: 14
Views: 484
Reputation: 2254
Although OP has proved it's impossible, we can cheat in modern languages.
a += b;
b -= b += b; // Negates b in most languages, but not in C
b += a;
a -= b;
Upvotes: 2
Reputation: 4510
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#?
Upvotes: 10