Below is some code from Codeacademy.com. There is something I don’t understand: Why does the value of is_prime not change with every iteration of the loop? For example, testing the number 8, it may be that the loop results in is_prime being false for values 2 and 3, but then for 4 it becomes false (because you can divide by 4). However, for 5,6 and 7 its true again. So why at the end of the loop does the value stay false even after 5,6 and 7 would make it be true again?
def prime(n)
puts "That's not an integer." unless n.is_a? Integer
is_prime = true
for i in 2..n-1
if n % i == 0
is_prime = false
end
end
if is_prime
puts "#{n} is prime!"
else
puts "#{n} is not prime."
end
end
prime(2)
prime(9)
prime(11)
prime(51)
prime(97)
The behavior you’re describing is what would happen if it was written like this:
But in your code there is no
else. If the number is not divisible, nothing happens so the variable stays like it was.