Why does the prime number test give '2' a pass as a prime?


#1

The code here

for i in 2..n-1
if n % i == 0
is_prime = false
end

would be satisfied for the numeral '2'. it would not leave a remainder for i = 2 to 1 or just 2 if the range cannot go downward.


#2

If n is 2, then the for i in 2..n-1 loop never runs, since n-1 == 1 is < 2. So if you initialize is_prime = true (that's missing in the code you give), 2 is declared to be prime, which is correct.


#3

Hi, I understand that a prime number is divisible exactly by itself and 1 but I don't really understand how this syntax works.
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

Can you please kindly explain further? So if n = 9 , does that mean i is in the range from 2 to 8? Then, does "n%1 ==0" means that this syntax will run from 9 % 8 , 9% %7.....until 9%2?

"if n% i == 0" means the result should not have any remainder (i.e. nil) then it is not a prime number since "is_prime = false"? But, not having any remainder can't determine whether it is a prime number or not right? I have been thinking this over and over again but still don't get it. Some help would be great.


#4

If n is 9, then the range is 2..8. It will run from 9 % 2 until 9 % 8.

Yes, as soon as there's no remainder, n is considered not prime. Since we used a range excluding the number itself and 1, we can be certain that if there's no remainder, it's another factor than those two, so n can't be prime.


#5

Ok, I understand now! Thanks a lot. =)


#6

Plus, 2 is a prime number, and this is a program to test if a number is prime. If 2 was not a prime number, it would have been very simple to change the code so 2 didn't pass, and they would have done that if that were the case


#7

Thanks! Sorry for the late reply, Codecademy's notification that i have received a reply (via email) doesn't seem to work for me.


#8

You're good. This is very ironic because I took quite a while to reply to this. Also, you're welcome