Last active
March 1, 2021 01:16
-
-
Save jasdev/5b8b83f23cdd2fb73ed6f6473a0f11f8 to your computer and use it in GitHub Desktop.
A sketch of a prime monomial search.
This file contains 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
extension BinaryInteger { | |
// Let’s assume we have `BinaryInteger.isPrime()` implemented. | |
func isPrime() -> Bool { /* … */ } | |
} | |
let possiblePrimeLastDigits = ["1", "3", "7", "9"] // Primes greater than five can’t have | |
// 0, 2, 4, 6, 8, or 5 in its one’s position. If it did, we’d have an even or a multiple | |
// of five in hand (assuming the prime is greater than five and we’re squarely in this | |
// territory since 5 _isn’t_ monomial). | |
let ms = (3...9).reversed() // The possible “m”s in the problem statement. We can | |
// safely ignore 2 since neither 12 or 21 are prime and we reverse the range | |
// since any prime in the upper end of the length range will be greater than monomial | |
// primes with a shorter length. | |
var largestPrimeMonomial: UInt? | |
outerLoop: for m in ms { | |
let mLengthMonomials = (1...m) | |
.reversed() | |
.map(String.init) | |
.permutations() // Let’s assume we have `Collection.permutations()` at hand. | |
// `mLengthMonomials` will contain single-digit strings, up to the current monomial | |
// length being considered. e.g. `[["1", "2", "3", "4"], ["2", "1", "3", "4"], …]`. | |
for monomial in mLengthMonomials { | |
guard | |
possiblePrimeLastDigits.contains(monomial.last!), // Last digit check. | |
let intMonomial = UInt(monomial.joined()), // Join the `String` digits | |
// and cast to an unsigned integer. | |
intMonomial > (largestPrimeMonomial ?? 0), | |
intMonomial.isPrime() | |
else { continue } | |
largestPrimeMonomial = intMonomial | |
break outerLoop // Once we’ve found a candidate prime, we can break out | |
// of the outer loop since we’re searching in decreasing order. | |
} | |
} | |
print(largestPrimeMonomial) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment