Jump to content

Sequence: smallest number with exactly n divisors: Difference between revisions

Added Swift solution
m (Phix/mpfr)
(Added Swift solution)
Line 1,378:
<pre>
[1, 2, 4, 6, 16, 12, 64, 24, 36, 48, 1024, 60, 4096, 192, 144]
</pre>
 
=={{header|Swift}}==
<lang swift>// See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
var power = 2
// Deal with powers of 2 first
while n % 2 == 0 {
total += 1
power *= 2
n /= 2
}
// Odd prime factors up to the square root
var p = 3
while p * p <= n {
var sum = 1
power = p
while n % p == 0 {
sum += 1
power *= p
n /= p
}
total *= sum
p += 2
}
// If n > 1 then it's prime
if n > 1 {
total *= 2
}
return total
}
 
let limit = 15
var sequence = Array(repeating: 0, count: limit)
var count = 0
var n = 1
while count < limit {
let divisors = divisorCount(number: n)
if divisors <= limit && sequence[divisors - 1] == 0 {
sequence[divisors - 1] = n
count += 1
}
n += 1
}
for n in sequence {
print(n, terminator: " ")
}
print()</lang>
 
{{out}}
<pre>
1 2 4 6 16 12 64 24 36 48 1024 60 4096 192 144
</pre>
 
1,777

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.