Prime triangle: Difference between revisions
Content added Content deleted
(Added Java solution) |
(Added Swift solution) |
||
Line 1,021: | Line 1,021: | ||
Elapsed time: 754 milliseconds |
Elapsed time: 754 milliseconds |
||
</pre> |
|||
=={{header|Swift}}== |
|||
<lang swift>import Foundation |
|||
func isPrime(_ n: Int) -> Bool { |
|||
guard n > 0 && n < 64 else { |
|||
return false |
|||
} |
|||
return ((UInt64(1) << n) & 0x28208a20a08a28ac) != 0 |
|||
} |
|||
func primeTriangleRow(_ a: inout ArraySlice<Int>) -> Bool { |
|||
let start = a.startIndex |
|||
let end = a.endIndex |
|||
if a.count == 2 { |
|||
return isPrime(a[start] + a[start + 1]) |
|||
} |
|||
for i in start + 1..<end - 1 { |
|||
if isPrime(a[start] + a[i]) { |
|||
a.swapAt(i, start + 1) |
|||
if primeTriangleRow(&a[start + 1..<end]) { |
|||
return true |
|||
} |
|||
a.swapAt(i, start + 1) |
|||
} |
|||
} |
|||
return false |
|||
} |
|||
func primeTriangleCount(_ a: inout ArraySlice<Int>) -> Int { |
|||
let start = a.startIndex |
|||
let end = a.endIndex |
|||
var count = 0 |
|||
if a.count == 2 { |
|||
if isPrime(a[start] + a[start + 1]) { |
|||
count += 1 |
|||
} |
|||
} else { |
|||
for i in start + 1..<end - 1 { |
|||
if isPrime(a[start] + a[i]) { |
|||
a.swapAt(i, start + 1) |
|||
count += primeTriangleCount(&a[start + 1..<end]) |
|||
a.swapAt(i, start + 1) |
|||
} |
|||
} |
|||
} |
|||
return count |
|||
} |
|||
func printRow(_ a: [Int]) { |
|||
if a.count == 0 { |
|||
return |
|||
} |
|||
print(String(format: "%2d", a[0]), terminator: "") |
|||
for x in a[1...] { |
|||
print(String(format: " %2d", x), terminator: "") |
|||
} |
|||
print() |
|||
} |
|||
for n in 2...20 { |
|||
var a = Array(1...n) |
|||
if primeTriangleRow(&a[...]) { |
|||
printRow(a) |
|||
} |
|||
} |
|||
print() |
|||
for n in 2...20 { |
|||
var a = Array(1...n) |
|||
if n > 2 { |
|||
print(" ", terminator: "") |
|||
} |
|||
print("\(primeTriangleCount(&a[...]))", terminator: "") |
|||
} |
|||
print()</lang> |
|||
{{out}} |
|||
<pre> |
|||
1 2 |
|||
1 2 3 |
|||
1 2 3 4 |
|||
1 4 3 2 5 |
|||
1 4 3 2 5 6 |
|||
1 4 3 2 5 6 7 |
|||
1 2 3 4 7 6 5 8 |
|||
1 2 3 4 7 6 5 8 9 |
|||
1 2 3 4 7 6 5 8 9 10 |
|||
1 2 3 4 7 10 9 8 5 6 11 |
|||
1 2 3 4 7 10 9 8 5 6 11 12 |
|||
1 2 3 4 7 6 5 12 11 8 9 10 13 |
|||
1 2 3 4 7 6 13 10 9 8 11 12 5 14 |
|||
1 2 3 4 7 6 13 10 9 8 11 12 5 14 15 |
|||
1 2 3 4 7 6 5 12 11 8 15 14 9 10 13 16 |
|||
1 2 3 4 7 6 5 12 11 8 9 10 13 16 15 14 17 |
|||
1 2 3 4 7 6 5 8 9 10 13 16 15 14 17 12 11 18 |
|||
1 2 3 4 7 6 5 8 9 10 13 16 15 14 17 12 11 18 19 |
|||
1 2 3 4 7 6 5 8 9 10 13 16 15 14 17 12 19 18 11 20 |
|||
1 1 1 1 1 2 4 7 24 80 216 648 1304 3392 13808 59448 155464 480728 1588162 |
|||
</pre> |
</pre> |
||