Last active
August 26, 2020 21:54
-
-
Save Frank-Buss/6913572a8c0c9d2c0bfe73480d92b9ed to your computer and use it in GitHub Desktop.
Ruby script which prints all happy numbers <= 100
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
#!/usr/bin/env ruby | |
# prints all happy numbers <= 100 | |
# https://en.wikipedia.org/wiki/Happy_number | |
# returns true, if the number is happy | |
def happy?(n) | |
n = n.digits.sum { |x| x * x } while n > 6 | |
n == 1 | |
end | |
# filter all numbers <= 100 for happiness and print the list | |
puts (1..100).select { |x| happy? x } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment