2

my problem is a &= b after searching internet for a while i found that its a bitwise and operator but cant figure out what its doing in this program

x = int(input("Insert first number: "))
y = int(input("Insert second number: "))

if x>y:
    x,y =x,y
elif x<y :
    x,y= y,x

while x != 0 and y != 0:
    if x > y:
        x %= y
    else:
        y &= x

GCD = x + y
print("The greatest common divisor = ",GCD)
khashayar
  • 23
  • 2
  • provided program does not compute GCD try sample (3, 5) -> gcd should be 1, this gets stuck in infinite loop check https://www.geeksforgeeks.org/gcd-in-python/ – the.eleplant Dec 10 '20 at 16:41

3 Answers3

2

@angelogro should answer your question.

I supplement on it.

"&" And Operator will keep all common `1` in two digits. 

eg.

3 = 0b011
7 = 0b111

3 & 7 will keep the last two 1 the answer should be 3.

beside this, the program you sent it got problem , u can try test case with

x= 17 y = 5

for finding GCD sample program from https://www.geeksforgeeks.org/gcd-in-python/ please check it out

def computeGCD(x, y): 
  
   while(y): 
       x, y = y, x % y 
  
   return x 
0

It's a the binary operation AND where the result of y&x is written to y. Here is an explanation to bitwise AND.

Example:

x=3
y=7

print(f"x in binary: {bin(x)}; y in binary: {bin(y)}")

Outputs: x in binary: 0b11; y in binary: 0b111

y&=x

print(f"x in binary: {bin(x)}; y in binary: {bin(y)}")

Outputs: x in binary: 0b11; y in binary: 0b11

angelogro
  • 124
  • 8
0

x %= y means x = x % y --- this is mod operator

x &= y means x = x & y --- this is bit-wise "and" operator. First two operands (integers) are converted into binary form. Then, bit-wise and operation is performed.