Skip to content

Instantly share code, notes, and snippets.

@proxpero
Last active October 11, 2015 01:37
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 proxpero/6069117b11820d4d30c1 to your computer and use it in GitHub Desktop.
Save proxpero/6069117b11820d4d30c1 to your computer and use it in GitHub Desktop.
Project Euler problem 44: Pentagonal Numbers (Xcode 7.0, Swift 2.0)
//: [Pentagonal Numbers](https://projecteuler.net/problem=44)
/*:
Pentagonal numbers are generated by the formula, P[n]=n[3n−1]/2. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P[4] + P[7] = 22 + 70 = 92 = P[8]. However, their difference, 70 − 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, P[j] and P[k], for which their sum and difference are pentagonal and D = |P[k] − P[j]| is minimised; what is the value of D?
*/
/*:
from [Wikipedia's article on Pentagonal Number](https://en.wikipedia.org/wiki/Pentagonal_number)
>The simplest way to test whether a positive integer x is a (non-generalized) pentagonal number is by computing
>![n = (sqrt(24.0 * Double(x) + 1.0) + 1.0) / 6.0](https://upload.wikimedia.org/math/f/e/4/fe488e73246b16817c149a101e8dd1f8.png)
>If n is a natural number, then x is the nth pentagonal number. If n is not a natural number, then x is not pentagonal.
*/
import Darwin
extension Int {
var pentagonal: Int {
return Int(Double(self * (3 * self - 1)) / 2)
}
var isPentagonal: Bool {
let result = (sqrt(24.0 * Double(self) + 1.0) + 1.0) / 6.0
return result == round(result)
}
}
outside: for k in (1..<Int.max) {
break // comment out this break to start in a playground, uncomment it to stop running. (play/stop in Xcode doesn't always work the way I want it to)
// Note: This was tedious to sit through in a playground (Xcode 7.0, swift 2.0) and it spun up my fan, so
// I stuck the code in a new command-line tool project and it finished instantaneously.
let pk = k.pentagonal
inside: for j in (1..<k) {
let pj = j.pentagonal
if !(pk + pj).isPentagonal {
continue inside
}
let diff = pk - pj
if !diff.isPentagonal {
continue inside
}
print("P(\(k)) = \(pk), P(\(j)) = \(pj), difference = \(diff)")
break outside
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment