Allen M - 1 year ago 68
Ruby Question

# Issue calculating Angstrom numbers in Ruby

Angstrom number example: 153;

`1**3 + 5**3 + 3**3 = 153`

``````puts "Enter a number: "
number = gets.chomp.to_i
initial_number = number
angstrom = 0
while (number % 10) != 0
number = number % 10
angstrom = angstrom + (number ** 3)
number = number / 10
end

puts angstrom
puts initial_number

if angstrom == initial_number
puts "YES ANGSTROM"
else
puts "NO ANGSTROM"
end
``````

EX: Input is 123

Entering while, we get 12 after the number % 10 statement. But, after that, it doesn't go into while again; why is that?
`12 % 10`
shouldn't come out to
`0`
.

`puts angstrom`
and
`puts initial_number`
lines just to check what's going on with the numbers.

I suspect you want something more along the lines of:

``````angstrom = 0
while number > 0
digit = number % 10
angstrom += digit ** 3
number /= 10
end
``````

to isolate each digit without destroying the number, and to avoid early termination from zeros contained internally in the input number.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download