This is very simple question

Rob Renaud rpgnmets at aol.com
Wed Apr 21 21:52:07 EDT 2004


"Fredrik Lundh" <fredrik at pythonware.com> wrote in message news:<mailman.843.1082564447.20120.python-list at python.org>...
> but a lousy subject.
> 
> "Eric" <ekoome at yahoo.com> 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]
>  
> >>> 8*4*1
> 32
> 
> > I would appreciate a fuction which would do this.
> 
> def func(x): return [2**i for i in range(3,0,-1) if x & 2**i]
> 
> </F>

The code is buggy, it won't work for odd numbers...

>>> func(5)
[4]

>>> def func(x): return [2**i for i in range(3,-1,-1) if x & 2**i]
... 
>>> func(5)
[4, 1]

But this still leaves us with numbers which are too big.

>>> func(243)
[2, 1]

So this should take care of it...

>>> def func(x): return [2**i for i in
range(int(math.log(x)/math.log(2)),-1,-1) if x & 2**i]

>>> func(323421234)
[268435456, 33554432, 16777216, 4194304, 262144, 131072, 65536, 1024,
32, 16, 2]
>>> sum(func(323421234))
323421234



More information about the Python-list mailing list