Magnanimous numbers: Difference between revisions
Content added Content deleted
m (Rust - simplified code) |
(Added Swift solution) |
||
Line 1,198: | Line 1,198: | ||
391st through 400th magnanimous numbers: |
391st through 400th magnanimous numbers: |
||
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081 |
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081 |
||
</pre> |
|||
=={{header|Swift}}== |
|||
{{trans|Rust}} |
|||
<lang swift>func isPrime(_ n: Int) -> Bool { |
|||
if n < 2 { |
|||
return false |
|||
} |
|||
if n % 2 == 0 { |
|||
return n == 2 |
|||
} |
|||
if n % 3 == 0 { |
|||
return n == 3 |
|||
} |
|||
var p = 5 |
|||
while p * p <= n { |
|||
if n % p == 0 { |
|||
return false |
|||
} |
|||
p += 2 |
|||
if n % p == 0 { |
|||
return false |
|||
} |
|||
p += 4 |
|||
} |
|||
return true |
|||
} |
|||
func isMagnanimous(_ n: Int) -> Bool { |
|||
var p = 10; |
|||
while n >= p { |
|||
if !isPrime(n % p + n / p) { |
|||
return false |
|||
} |
|||
p *= 10 |
|||
} |
|||
return true |
|||
} |
|||
func pad(string: String, width: Int) -> String { |
|||
if string.count >= width { |
|||
return string |
|||
} |
|||
return String(repeating: " ", count: width - string.count) + string |
|||
} |
|||
let m = (0...).lazy.filter{isMagnanimous($0)}.prefix(400); |
|||
print("First 45 magnanimous numbers:"); |
|||
for (i, n) in m.prefix(45).enumerated() { |
|||
if i > 0 && i % 15 == 0 { |
|||
print() |
|||
} |
|||
print(pad(string: String(n), width: 3), terminator: " ") |
|||
} |
|||
print("\n\n241st through 250th magnanimous numbers:"); |
|||
for n in m.dropFirst(240).prefix(10) { |
|||
print(n, terminator: " ") |
|||
} |
|||
print("\n\n391st through 400th magnanimous numbers:"); |
|||
for n in m.dropFirst(390) { |
|||
print(n, terminator: " ") |
|||
} |
|||
print() |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
First 45 magnanimous numbers: |
|||
0 1 2 3 4 5 6 7 8 9 11 12 14 16 20 |
|||
21 23 25 29 30 32 34 38 41 43 47 49 50 52 56 |
|||
58 61 65 67 70 74 76 83 85 89 92 94 98 101 110 |
|||
241st through 250th magnanimous numbers: |
|||
17992 19972 20209 20261 20861 22061 22201 22801 22885 24407 |
|||
391st through 400th magnanimous numbers: |
|||
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081 |
|||
</pre> |
</pre> |
||