medvedNick
medvedNick

Reputation: 4510

Is it possible to swap two variables with only += and -= no other operators or variables?

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

Answers (3)

Tom
Tom

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

medvedNick
medvedNick

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:

  1. a-=a. One line becomes 0, so det=0
  2. a+=a. That means multiplying a line by 2, so the det A'= 2*det A
  3. a+=b. That means elementary transformation, which does not change the value of det
  4. 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

tomato
tomato

Reputation: 749

    a +=b;
    b -=a;
    b =-b;
    a -=b;

Upvotes: 0

Related Questions