This is very simple question
Gyro Funch
gyromagnetic at excite.com
Wed Apr 21 12:42:38 EDT 2004
Eric wrote:
> I would want to obtain a list of factors (multiples of 2) given a
> prime number in python.
>
> For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1]
>
> I would appreciate a fuction which would do this.
>
> Eric
Below is an ugly and inefficient implementation.
-g
def i2b(i):
s = ''
while i:
s = (i & 1 and '1' or '0') + s
i >>= 1
return s or '0'
def find_factors(val):
bstr = i2b(val)
facs = [int(j)*2**i for (i,j) in enumerate(bstr[::-1]) if
int(j) != 0]
facs.reverse()
return facs
if __name__ == '__main__':
print find_factors(13) == [8,4,1]
print find_factors(5) == [4,1]
print find_factors(7) == [4,2,1]
print find_factors(15) == [8,4,2,1]
More information about the Python-list
mailing list