Allen M - 1 year ago 120

Ruby Question

`puts "Enter range(starts at 1), ends at the number that you enter: "`

range = gets.chomp.to_i

number = 1

while number <= range

temporary_number = number

sum_angstrom = 0

number += number

while(temporary_number != 0)

digit = temporary_number % 10

temporary_number /= 10

sum_angstrom = sum_angstrom + (digit ** 3)

end

if (sum_angstrom == number)

puts number

end

end

This time, I tried to make a program to show the armstrong numbers in a range that's taken from the user's input. The program just stops after I enter the number and press enter and i can't figure out why.

Keep in mind that i can't use for(each), that's why i'm using while so often.

Answer Source

First of all, change `number += number`

to `number += 1`

; otherwise you will only test the powers of 2.

Second, move the `number += 1`

line at the bottom of the while block it is in. Otherwise you will always test if `sum_armstrong(n) == n+1`

.

This works:

```
puts "Enter range(starts at 1), ends at the number that you enter: "
range = gets.chomp.to_i
number = 1
while number <= range
temporary_number = number
sum_angstrom = 0
while(temporary_number != 0)
digit = temporary_number % 10
temporary_number /= 10
sum_angstrom = sum_angstrom + (digit ** 3)
end
if (sum_angstrom == number)
puts number
end
number += 1
end
```