473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

This is very simple question

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
Jul 18 '05 #1
16 1577
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


Eric,
Is the last test 17 vs 15?
With not much checking:
13 [8, 4, 1]
5 [4, 1]
7 [4, 2, 1]
17 [16, 1]


#------------------------------------------------------------------
import math

#For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1]
#For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 17=[16,1]

def LargestPrimeLessThanOrEqualTo(n):
i = 0
while 1:
x = int(math.pow(2,i))
if x == n:
return x
if x > n:
return prevx
prevx = x
i += 1

def foo(x):
list = []
temp = x
while(temp > 0):
z = LargestPrimeLessThanOrEqualTo(temp)
temp -= z
list.append(z)
return list

for x in [13,5,7,17]:
print x,foo(x)

wes

Jul 18 '05 #2
I'm not sure those are factors? But then again I never was good at math

for say 13 you could just count up by two and then find the largest
number you can make of the twos and then move down until you find the
next one and then add 1 say you start with 13=[2,2,2,2,2,2,1] ?

then you know you have [12,1] 12 is a multiple of 2 or do you want
powers? if you want powers you could make the nessisary logic adjustments

Why exactly do you want this anyways?

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

Jul 18 '05 #3
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]
Jul 18 '05 #4
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.


If we told you it wouldn't be fair to the other students in your class :-)

Cheers,
Brian
Jul 18 '05 #5
but a lousy subject.

"Eric" <ek****@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>


Jul 18 '05 #6
In article <ma**************************************@python.o rg>,
Brian Quinlan <br***@sweetapp.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]

I would appreciate a fuction which would do this.


If we told you it wouldn't be fair to the other students in your class :-)

Jul 18 '05 #7
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


Eric,
To be less illustrative and somewhat more efficient.
wes

import math

def ListOfPowersLessThan(n):
list = []
i = 0
while True:
x = int(math.pow(2,i))
if x <= n:
list.append(x)
else:
break
i += 1
return list

TEST = [13,5,7,15,17,33]
powers = ListOfPowersLessThan( max(TEST) )
powers.reverse()

for x in TEST:
sum = 0
list = []
for s in powers:
if (sum + s) <= x:
sum += s
list.append(s)
if sum >= x:
break
print x,list
13 [8, 4, 1]
5 [4, 1]
7 [4, 2, 1]
15 [8, 4, 2, 1]
17 [16, 1]
33 [32, 1]


Jul 18 '05 #8
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


import math

def foo(n):
list = []
while n > 0:
x = int(math.log(n,2))
pow = int(math.pow(2,x))
list.append(pow)
n -= pow
return list

for x in [13,5,7,15,17,33]:
print x, foo(x)

13 [8, 4, 1]
5 [4, 1]
7 [4, 2, 1]
15 [8, 4, 2, 1]
17 [16, 1]
33 [32, 1]


Jul 18 '05 #9
ek****@yahoo.com (Eric) wrote in message news:<b0**************************@posting.google. com>...
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


Minor quibble: you don't mean factors. The only factors of a prime
number are the number itself and one; that's the definition of a prime
number.

Now, do you want a list of all powers of 2 less than a prime number,
OR do you want a list of powers of 2 such that the sum of the numbers
is the given prime number? For Mersienne primes, which are of the
form (2**n-1) the answer is the same either way. All your examples
are Mersienne primes.
But look at 11:
11 = 8 + 2 + 1, not 8 + 4 + 2 + 1

Of course, any odd number can be expressed as 2 + 2 + ... + 1, so what
you would really want is the shortest list of powers of 2 that add up
to the prime.
Jul 18 '05 #10
"Fredrik Lundh" <fr*****@pythonware.com> wrote in message news:<ma**************************************@pyt hon.org>...
but a lousy subject.

"Eric" <ek****@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
Jul 18 '05 #11

"Cameron Laird" <cl****@lairds.com> a écrit dans le message de news:10*************@corp.supernews.com...
In article <ma**************************************@python.o rg>,
Brian Quinlan <br***@sweetapp.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]

I would appreciate a fuction which would do this.


If we told you it wouldn't be fair to the other students in your class :-)

.
.
.
I'm surprised only one of the responses I've seen so far has
objected to what sure seems like an inappropriate response to
classwork. I'm astonished that no one is reading this question
as I do. I leave as an exercise for readers this generalization
of what *I* think is going on:

def positional_addends(positive_integer, base = 2):
result = []
current = 1
while positive_integer:
remainder = positive_integer % (base * current)
if remainder:
result.append(remainder)
positive_integer -= remainder
current *= base
result.reverse()
return result

print positional_addends(13)
print positional_addends(5)
print positional_addends(7)
print positional_addends(15)
print positional_addends(78904, 10)

The real exercise is to convert this to a readable one-liner,
at least for the binary case.
--

Cameron Laird <cl****@phaseit.net>
Business: http://www.Phaseit.net


You can also use divmod :

def decompose(i,base=2):
result=[]
factor=1
while i>0:
i,r=divmod(i,base)
if r:
result.append(r*factor) # or result.extend([factor]*r), depending on style
factor*=base
return result.reverse() # if you really want it reversed

Regards,
Nicolas
Jul 18 '05 #12
In article <40***********************@news.easynet.fr>,
Nicolas Lehuen <ni************@thecrmcompany.com> wrote:
Jul 18 '05 #13
> > return result.reverse() # if you really want it reversed

I agree that divmod() improves the algorithm, and thank
you for pointing that out.

I'm reasonably certain that the return value of reverse()
is not what you believe it to be.
--

Cameron Laird <cl****@phaseit.net>
Business: http://www.Phaseit.net


Ooops indeed, reverse() always returns None, because the reverse is made in place. I did test the program without the reverse, so I missed this mistake. Thanks !

BTW, I've been bitten by this behaviour a lot since I've switched to Python a year ago (coming from C++ and Java)... I would feel much better if reverse(), sort() and so on returned the list itself ; but then maybe other people would think the reversing/sorting etc. would not be done in place...

Regards,
Nicolas
Jul 18 '05 #14
cl****@lairds.com (Cameron Laird) wrote in message news:<10*************@corp.supernews.com>...
In article <ma**************************************@python.o rg>,
Brian Quinlan <br***@sweetapp.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]

I would appreciate a fuction which would do this.


If we told you it wouldn't be fair to the other students in your class :-)

.
.
.
I'm surprised only one of the responses I've seen so far has
objected to what sure seems like an inappropriate response to
classwork. I'm astonished that no one is reading this question
as I do. I leave as an exercise for readers this generalization
of what *I* think is going on:

def positional_addends(positive_integer, base = 2):
result = []
current = 1
while positive_integer:
remainder = positive_integer % (base * current)
if remainder:
result.append(remainder)
positive_integer -= remainder
current *= base
result.reverse()
return result

print positional_addends(13)
print positional_addends(5)
print positional_addends(7)
print positional_addends(15)
print positional_addends(78904, 10)

The real exercise is to convert this to a readable one-liner,
at least for the binary case.


I'm not quite sure, if I understood, what you mean.
One-liners ... OK.
Readable ??? Mmmhm ??
i2b=lambda num,s=[],i=1:num and i2b(num>>1,(num &1) and [(num &1)*i]+s
or s,i<<1) or s
i2b(13) [8, 4, 1] i2b(15) [8, 4, 2, 1]

Let's test it in general: sum=lambda l:reduce(lambda x,y:x+y,l,0)
sum([8, 4, 2, 1]) 15 for i in range(1,100000): .... if sum(i2b(i))!=i:
.... print 'i=%d: sum(i2b(i))=%d' % (i,sum(i2b(i)))
.... break
.... else:
.... print 'OK'
....
OK


Regards
Peter
Jul 18 '05 #15
On Thu, 22 Apr 2004 16:53:55 +0200, "Nicolas Lehuen"
<ni************@thecrmcompany.com> wrote:
> return result.reverse() # if you really want it reversed


I agree that divmod() improves the algorithm, and thank
you for pointing that out.

I'm reasonably certain that the return value of reverse()
is not what you believe it to be.
--

Cameron Laird <cl****@phaseit.net>
Business: http://www.Phaseit.net


Ooops indeed, reverse() always returns None, because the reverse is made in place. I did test the program without the reverse, so I missed this mistake. Thanks !

BTW, I've been bitten by this behaviour a lot since I've switched to Python a year ago (coming from C++ and Java)... I would feel much better if reverse(), sort() and so on returned the list itself ; but then maybe other people would think the reversing/sorting etc. would not be done in place...

Regards,
Nicolas

You probably already do this, but in case someone else wants an easy
workaround:

def reversed(lst):
lst2 = lst[:]
lst2.reverse()
return lst2

def sorted(lst):
lst2 = lst[:]
lst2.sort()
return lst2

Then you can do things like:
mylst = reversed(mylst)

Which is not as pretty as
mylst = mylist.reversed()

But it is less punctuation! ;-)

There's been talk about adding this type of method to the builtin list
object.
--dang
Jul 18 '05 #16
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.**********@worldnet.att.net

Jul 18 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: aj | last post by:
I currently have 2 official DB2 Workgroup Edition licenses for my 2 v8 production servers. I also have tech support/software upgrade agreements in place for both servers. I am interested in...
10
by: Randy | last post by:
I have asked a number of questions as a newbie trying to learn Access. Some folks have been very helpful with very direct and simple answers that help alot. Others give me answers with extensive...
113
by: Bonj | last post by:
I was in need of an encryption algorithm to the following requirements: 1) Must be capable of encrypting strings to a byte array, and decyrpting back again to the same string 2) Must have the same...
14
by: John | last post by:
Hi We have an SBS2000 server which has an access database running internally, supporting around 20 users. The server is connected to a broadband connection. Is it viable for us to run an asp.net...
9
by: JohnSmith | last post by:
I suspect this is easy, but I have been stumped for a day trying to solve this.. I want to be able to have an unlimited number of aspx pages that all use the code in one class file. I want code...
59
by: Alan Silver | last post by:
Hello, This is NOT a troll, it's a genuine question. Please read right through to see why. I have been using Vusual Basic and Classic ASP for some years, and have now started looking at...
19
by: Andy B | last post by:
Hello, Sorry for this newbish question. Briefly, my problem: ------------------ I expect the database I'm working on to reach something in the order of 12-16 Gigabytes, and I am interested...
16
by: lovecreatesbeauty | last post by:
`Writing C code is very simple', one guy related to my work said. I'm not sure whether he is an expert or not. What he said about C programming like this can't convince me. I think there should be...
28
by: Mike Hofer | last post by:
I've been maintaining some source code, and I've noticed some radical inconsistency in the code, particularly in the way that parameters are validated. I've noticed that this seems to have been...
13
by: aaragon | last post by:
Hi everyone, I just wanted to know if there is any difference in performance in declarating the variables in the beginning of a function or within for loops. For example: double test() {...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.