Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

swap

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?

like image 807
medvedNick Avatar asked May 21 '13 09:05

medvedNick


People also ask

How do you swap two numbers without variables?

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.

Can we swap 2 variables without a third one?

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.

Can you try to write a code to swap variables without using a third variable using the operator?

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.


1 Answers

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#?

like image 189
medvedNick Avatar answered Oct 11 '22 00:10

medvedNick