>> and << operators?

M

Medardo Rodriguez (Merchise Group)

What does >> and << do?

Normally they are bitwise operators:<< Shifts bits left

print 1 << 3
8

because 8 = 00001000 in binary

Regards
 
M

Mensanator

Normally they are bitwise operators:>> Shifts bits right

<< Shifts bits left

print 1 << 3
8

because 8 = 00001000 in binary

Regards

An example of usage:

import gmpy
def Collatz(n):
#
# if n is odd, multiply by 3 and add 1
# if n is even, divide by 2 until n becomes odd
# repeat until n == 1
#
while n>1:
print n,
f = gmpy.scan1(n) # find position of first 1-bit
if f>0: # it's even, so...
n = n >> f # ...remove factors of 2 in one fell swoop
else: # it's odd
n = 3*n + 1
print n

print 'Collatz(11):',
Collatz(11)

print

print 'Collatz(27):',
Collatz(27)

## Collatz(11): 11 34 17 52 13 40 5 16 1
##
## Collatz(27): 27 82 41 124 31 94 47 142 71
## 214 107 322 161 484 121 364
## 91 274 137 412 103 310 155
## 466 233 700 175 526 263 790
## 395 1186 593 1780 445 1336
## 167 502 251 754 377 1132 283
## 850 425 1276 319 958 479 1438
## 719 2158 1079 3238 1619 4858
## 2429 7288 911 2734 1367 4102
## 2051 6154 3077 9232 577 1732
## 433 1300 325 976 61 184 23 70
## 35 106 53 160 5 16 1
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top