This is very simple question
Al Schapira
a.d.schapira at worldnet.att.net
Mon Jun 7 03:02:17 CEST 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
What you seem to want are the powers of 2 that add up to the given
number. These are the powers of two that correspond to 1's in the binary
representation of the given number (integer).
$ cat foo.py
powerlist = [1 << (30-i) for i in range(31)] # [... 32, 16, 8, 4, 2, 1]
for x in [13,5,7,15,17,33]:
print x, [x & i for i in powerlist if x & i]
$ python < foo.py
13 [8, 4, 1]
5 [4, 1]
7 [4, 2, 1]
15 [8, 4, 2, 1]
17 [16, 1]
33 [32, 1]
Is this horse dead yet?
-Al Schapira, a.d.schapira at worldnet.att.net
More information about the Python-list
mailing list