Factors of an integer: Difference between revisions
Content added Content deleted
m (→{{header|Phix}}: added some larger number examples) |
(→Python: a bit faster by avoiding sets and sorting) |
||
Line 5,577: | Line 5,577: | ||
Much better (realize that factors come in pairs, the smaller of which is no bigger than sqrt(n)): |
Much better (realize that factors come in pairs, the smaller of which is no bigger than sqrt(n)): |
||
<syntaxhighlight lang="python"> |
<syntaxhighlight lang="python">from math import isqrt |
||
def factor(n): |
|||
factors1, factors2 = [], [] |
|||
for x in range(1, isqrt(n)): |
|||
if n % x == 0: |
if n % x == 0: |
||
factors1.append(x) |
|||
factors2.append(n // x) |
|||
x += 1 |
|||
return sorted(factors) |
|||
if x * x == n: |
|||
factors1.append(x) |
|||
⚫ | |||
factors1.extend(reversed(factors2)) |
|||
return factors1 |
|||
for i in 45, 53, 64: |
|||
⚫ | |||
45: factors: [1, 3, 5, 9, 15, 45] |
45: factors: [1, 3, 5, 9, 15, 45] |
||
53: factors: [1, 53] |
53: factors: [1, 53] |
||
64: factors: [1, 2, 4, 8, 16, 32, 64]</ |
64: factors: [1, 2, 4, 8, 16, 32, 64]</pre> |
||
More efficient when factoring many numbers: |
More efficient when factoring many numbers: |