Last active
October 11, 2015 01:37
-
-
Save proxpero/6069117b11820d4d30c1 to your computer and use it in GitHub Desktop.
Project Euler problem 44: Pentagonal Numbers (Xcode 7.0, Swift 2.0)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: [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 | |
> | |
>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