Count in factors: Difference between revisions
Content added Content deleted
(Add Swift) |
|||
Line 3,825: | Line 3,825: | ||
say "#{i} = #{Counter().factors(i).join(' × ')}" |
say "#{i} = #{Counter().factors(i).join(' × ')}" |
||
}</lang> |
}</lang> |
||
=={{header|Swift}}== |
|||
<lang swift>extension BinaryInteger { |
|||
@inlinable |
|||
public func primeDecomposition() -> [Self] { |
|||
guard self > 1 else { return [] } |
|||
func step(_ x: Self) -> Self { |
|||
return 1 + (x << 2) - ((x >> 1) << 1) |
|||
} |
|||
let maxQ = Self(Double(self).squareRoot()) |
|||
var d: Self = 1 |
|||
var q: Self = self & 1 == 0 ? 2 : 3 |
|||
while q <= maxQ && self % q != 0 { |
|||
q = step(d) |
|||
d += 1 |
|||
} |
|||
return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] |
|||
} |
|||
} |
|||
for i in 1...20 { |
|||
if i == 1 { |
|||
print("1 = 1") |
|||
} else { |
|||
print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " x "))") |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<pre>1 = 1 |
|||
2 = 2 |
|||
3 = 3 |
|||
4 = 2 x 2 |
|||
5 = 5 |
|||
6 = 2 x 3 |
|||
7 = 7 |
|||
8 = 2 x 2 x 2 |
|||
9 = 3 x 3 |
|||
10 = 2 x 5 |
|||
11 = 11 |
|||
12 = 2 x 2 x 3 |
|||
13 = 13 |
|||
14 = 2 x 7 |
|||
15 = 3 x 5 |
|||
16 = 2 x 2 x 2 x 2 |
|||
17 = 17 |
|||
18 = 2 x 3 x 3 |
|||
19 = 19 |
|||
20 = 2 x 2 x 5</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |