Skip to content

Instantly share code, notes, and snippets.

@stripe-q
Created August 25, 2017 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stripe-q/169588ebba83955adb29b4c9c9e44011 to your computer and use it in GitHub Desktop.
Save stripe-q/169588ebba83955adb29b4c9c9e44011 to your computer and use it in GitHub Desktop.
오일러 프로젝트 27번 풀이
import Foundation
func timeit(_ f: () -> ()) {
let s = Date()
f()
print("time: \(s.timeIntervalSinceNow * -1000)ms")
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
if (2...3) ~= n { return true }
if n % 2 == 0 || n % 3 == 0 { return false }
if n < 10 { return true }
var k = 5
let l = Int(sqrt(Double(n)) + 0.5)
while k <= l {
if n % k == 0 || n % (k + 2) == 0 { return false }
k += 6
}
return true
}
func test(_ a: Int, _ b: Int) -> Int {
let eq: (Int) -> Bool = { n -> Bool in
let k = n * n + a * n + b
return isPrime(k)
}
var n = 0
while true {
if eq(n) {
n += 1
} else {
return n
}
}
}
func solve() {
var m = 0
var result = 0
for a in stride(from: -1, through:-500, by: -1) {
for b in ((-2*a)...1000) {
let n = test(a, b)
if n > m {
m = n
result = a * b
}
}
}
print(result)
}
timeit(solve)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment