Created
May 4, 2015 23:22
-
-
Save nagelflorian/7eb2201893a2259ceb97 to your computer and use it in GitHub Desktop.
Happy Numbers in Swift
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
// Happy Numbers | |
// info: http://en.wikipedia.org/wiki/Happy_number | |
// by Florian Nagel | |
// floriannagel.net | |
import Foundation | |
func isHappyNumber(var number: Int) -> Bool { | |
var history = [Int]() | |
while number != 1 { | |
history.append(number) | |
var sum: Int = 0 | |
while number != 0 { | |
sum += Int(pow(Double(number%10), 2.0)) | |
number /= 10 | |
} | |
number = sum | |
if contains(history, number) { | |
return false | |
} | |
} | |
return true | |
} | |
func print8HappyNumbers(var start: Int) { | |
var found = 0 | |
while found < 8 { | |
if isHappyNumber(start) { | |
println(start) | |
found++ | |
} | |
start++ | |
} | |
} | |
print8HappyNumbers(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment