I have written a small practice Python script to determine the prime numbers between 2-10, for practice. Although I have pored over this script numurous times, I have not found the problem.
The problem is: Python will not print "is a prime" when a number is a prime. After examining the code below, this will make sense..
for i in range(2,10):
print
print i,"-",
for j in range(2,i):
if (i % j) == 0:
print j,
else:
if j == i + 1:
print "is a Prime"
On execution, it prints this:
2 -
3 -
4 - 2
5 -
6 - 2 3
7 -
8 - 2 4
9 - 3
Note:I am using the Windows 98 IDLE GUI. I am not sure if this is affecting it..
I believe line 8 may be a problem. I am not sure whether to use "j - 1 == i" or j == i + 1".
I too do not know python. But it looks like you line "for j in range(2,i)" will vary j starting at 2 and going up to either i or i-1, I'm not sure which from this thread. But either way, it looks like your final test in the loop is to see if j equals i+1. How can that ever happen?
In any event, your problem isn't python, it's the algorithm. Your inner loop is finding factors. Before you enter that inner loop, set "nfactor=0". Each time you find a factor and do the "print j", also increment nfactor. After the inner loop finishes, test nfactor...if it's zero, "print prime".