What does this cycle do?

What does the next cycle do?

k = 0
while(b!=0): 
   a = a^b 
   b = (a & b) << 1 
   k = k + 1 

where a, band kintegers.

Initially a= 2 779 and b= 2 62 then what will be the value kafter the end of the cycle?

I will be glad if you try to solve the problem manually, and not programmatically.

EDIT : removing c and C ++ tags. How can I solve the problem manually?

+3
source share
6 answers

After executing this snippet:

a = a^b ;
b = (a & b) << 1;

b , b a. , 2 xa a + b, b 2 (- ). , , MSB a b ( 780- ). b 63- , 718 : 780 - 63 + 1 ( ) = 718.

, a= 2 1 b= 2 0:

a = 10
b = 01
k = 0

a = 11
b = 10
k = 1

a = 01 (a + b no longer holds here, but it is irrelevant as this is the termination case)
b = 00
k = 2
+4

?

[ a] - [ b] + 1

, . a = 2 10 b = 2 5 :

k =  0, a = 10000000000, b =       100000
k =  1, a = 10000100000, b =      1000000
k =  2, a = 10001100000, b =     10000000
k =  3, a = 10011100000, b =    100000000
k =  4, a = 10111100000, b =   1000000000
k =  5, a = 11111100000, b =  10000000000

- ideone.com.

, , k = 718.

+2

, , , 718, .

0

, , k 1 .

.

, .

0

, qnd b , , 2 779 , , b 2 62. , , a = a ^ b; b = (a b) < 1; a be 0. k 1. b 0, while .

EDIT: , C/++ #

0

C. , , @Paul. , ,

a + b == (a^b) + ((a&b) << 1)

where a^bis the amount without transfer from each bit, but (a&b)<<1transferred from each bit, we can say that it carries the amount, IFF C-code will be

int k = 0;
while(b){ 
   int old_a = a;
   a = a^b;
   b = (old_a & b) << 1; // note that the need the original value of a here
   k++;  // number of recursion levels for carry
};

The difference in code may be caused by a "parallel" way of executing in the source code (or language).

0
source

Source: https://habr.com/ru/post/1779716/


All Articles