Ask Your Question
3

List of prime factors with repetition

asked 2016-05-21 16:14:39 +0100

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

Is there a simple command on Sage wich gives, in place of factor(720)= 2^4 * 3^2 * 5, the list [2, 2, 2, 2, 3, 3, 5] of prime factors with repetition?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
4

answered 2016-05-23 03:48:30 +0100

slelievre gravatar image

updated 2016-05-23 18:55:12 +0100

Some potentially useful variations, building on previous answers and comments by @calc314 and @logomath.

The function factor returns a factorization.

sage: F = factor(2016)
sage: F
2^5 * 3^2 * 7

This secretly wraps a list of pairs (prime, multiplicity), and you can get this list.

sage: list(F)
[(2, 5), (3, 2), (7, 1)]

You can also iterate through this list of pairs directly.

sage: for pm in F: print pm
(2, 5)
(3, 2)
(7, 1)

This means you can use list comprehension in smart ways.

sage: [f[0] for f in F for _ in range(f[1])]
[2, 2, 2, 2, 2, 3, 3, 7]

Same as above, but calling (p, m) the pairs.

sage: [p for (p, m) in F for _ in range(m)]
[2, 2, 2, 2, 2, 3, 3, 7]

Getting a list of repetitions of each prime.

sage: [([p] * m) for (p, m) in F]
[[2, 2, 2, 2, 2], [3, 3], [7]]

Flattening it to get the list of prime factors with multiplicity.

sage: flatten([([p] * m) for (p, m) in F])
[2, 2, 2, 2, 2, 3, 3, 7]

Using add to sum lists starting from the empty list (included as an optional parameter to add).

sage: add([[p] * m for (p, m) in F], [])
[2, 2, 2, 2, 2, 3, 3, 7]

(Edit.) Same but using an iterator instead of a list.

sage: add(([p] * m for (p, m) in F), [])
[2, 2, 2, 2, 2, 3, 3, 7]
edit flag offensive delete link more

Comments

Thank you, very interesting how sage is full of options. As I am using it for very large n, I remarked that the version " add([[p] ..." is nearly tenfold slower than the others (n near to 10000 digits).

logomath gravatar imagelogomath ( 2016-05-23 13:39:17 +0100 )edit
2

answered 2016-05-21 18:30:35 +0100

calc314 gravatar image

I don't know of a direct command. Here is one option, though.

F= factor(2016)
result=[f[0] for f in F for i in range(f[1])]
result

You may wish to look up the factor command for more details and examples.

edit flag offensive delete link more

Comments

Thank you, seems nice

logomath gravatar imagelogomath ( 2016-05-22 08:03:45 +0100 )edit

I just add here a lambda-version of it for reference:

result = lambda n: [f[0] for f in factor(n) for i in range(f[1])]; result(2016)

logomath gravatar imagelogomath ( 2016-05-22 11:07:31 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2016-05-21 16:14:39 +0100

Seen: 7,956 times

Last updated: May 23 '16