Skip to content

Instantly share code, notes, and snippets.

@squiidz
Last active March 25, 2017 22:00
Show Gist options
  • Save squiidz/2595e2aa2d174ba7c70bfe6e3f22263a to your computer and use it in GitHub Desktop.
Save squiidz/2595e2aa2d174ba7c70bfe6e3f22263a to your computer and use it in GitHub Desktop.
armstrong numbers in ruby
# num = 1234
# num_length = Math.log(num, 10).ceil => 4
# base = 10 ** (num_length - 1) => 1000
def is_armstrong(num)
if (1..9).include?(num)
return true
elsif num == 10
return false
end
num_c = num
num_length = Math.log(num, 10).ceil
len = num_length
acc = []
while len != 0
base = 10 ** (len - 1)
diff = (num_c / base)
#puts "num: #{num}, numc: #{num_c}, len: #{len}, base: #{base}, diff: #{diff}"
acc.push(diff ** num_length)
num_c -= (diff * base)
len -= 1
end
acc.reduce(:+) == num
end
(1..999).each do |n|
if is_armstrong(n)
puts "Number: #{n} => true"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment