1 | initial version |
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]
2 | No.2 Revision |
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]