Factors of an integer: Difference between revisions

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

edits