Last active
June 5, 2021 09:45
-
-
Save withs/0e4f84bd185cce99e6555894808c77fb to your computer and use it in GitHub Desktop.
Simple script wich try all 4x4 mumbers and get the highest palindrome of it in Swift
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
/* | |
Simple script wich try all 4x4 mumbers and get the highest palindrome of it. | |
- results: 4x4 numbers (Imac 2013, i5, swift 5.3.2) | |
Highest palindrome -> 99000099 | |
Found in -> 240.52266907691956 seconds | |
- results: 4x4 numbers (Macbook air 2020, M1, swift 5.4) | |
Highest palindrome -> 99000099 | |
Found in -> 92.4186509847641 seconds | |
- results: 4x4 numbers (Ipad pro 2018, A12X, swift playground) | |
Highest palindrome -> 99000099 | |
Found in -> 160.87225997447968 seconds | |
*/ | |
import Foundation | |
/** | |
Function to test if a number is palindrome | |
- parameter number: (Int) The number to check | |
- returns: (Bool) Result if the number is palindrome | |
- notes : Cast the int entry to a str to a list wich got reversed and | |
the list is joined to a string casted to an int and check if the entry is | |
equal to the reversed entry. | |
*/ | |
func isPalindrome(number: Int) -> Bool { | |
return Int(String(String(number).reversed()))! == number | |
} | |
let startTime = Date().timeIntervalSinceReferenceDate | |
var highestPalindrome = 0 | |
for i in 1000...9999 { | |
for s in 1000...9999 { | |
let r = i*s | |
if isPalindrome(number: r) && r > highestPalindrome { | |
highestPalindrome = r | |
} | |
} | |
} | |
let endTime = Date().timeIntervalSinceReferenceDate | |
print("Highest palindrome -> \(highestPalindrome)") | |
print("Found in -> \(endTime - startTime) seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment