So I’ve got this snippet of code. And it works (It says 1 is non-prime).:
n = 1
s = 'prime'
for i in range(2, n / 2 + 1):
if n == 1 or n % i == 0:
s= 'non-' +s
break
print s
My problem is that if I change the fourth line to: if n % i == 0 or n == 1:, it doesn’t work (it says 1 is prime.)
Why is that? Since I’m using or should it be that either one of them is True so the order doesn’t count?
(I’m still learning about boolean so I may be making some basic mistake.)
Thanks in advance!
EDIT: Thanks for the answers; I never realized my issue with the range() function. And about the code working and not working: I have no idea what happened. I may have made some mistake somewhere along the way (maybe forgot to save before running the script. Although I could’ve sworn that it worked differently 😛 ). Maybe I’m just getting tired…
Thanks for the answers anyways!
The precedence is fine.
%is evaluated first, then==, thenor, so it breaks down into:Your problem is that your
forloop is not being executed at all, so thatsis still set to"prime".The range
2,n/2+1whennis 1 equates to2,1which will result in the body not being executed.In fact it won’t be executed where
nis 2 either since2/2+1is 2 and the range2,2doesn’t execute. The values are the start and terminating value, not start and end (last) value – it’s just fortuitous there that 2 is considered a prime by virtue of the initialisation ofs🙂Try this instead:
It’s wasteful going all the way up to
n/2, the square root ofnis all that’s needed.