Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 14 Online
OpenStudy (anonymous):

problem set 1: i thought i figured out a test to see if a number is prime but now i'm having problems with the script. If I enter a prime number, I get the correct answer (I included a print statement to indicate when a number is prime.) If I enter any other number, the script either runs indefinitely until I force it to quit or I get a false positive. Here's a link to my current script: http://dpaste.com/524568/ I most recently ran the test with the number 8 and got the statement: "8 is a prime number." Does anyone see what I'm doing wrong here?

OpenStudy (anonymous):

Well, what happens when you've given it a number like 8? It will execute the first line, assigning divisor the value 3. Then it will ask "Is 3 < 8/2?", and since it is it will execute the block for the loop. The loop block first asks, "Is 8%3 != 0?". Since 8%3 is 2 and therefore not 0, it will execute assign divisor the value 3 + 1, or 4. Then it will ask "Is 4 < 8/2?". Since 4 is 8/2 this will fail and the loop will end. Then it will claim 8 is prime. I think it would be helpful and informative to insert some print statements to see the value of x and divisor at each step along the way.Something like: print 'In loop: x=', x, ', divisor=', divisor # between lines 3 & 4. and also print 'x%divisor was', x%divisor, ' so incrementing divisor' #between lines 4 & 5.

OpenStudy (anonymous):

polpak, i will try this technique. i keep thinking i need to create a print statement for when the isprime test fails and exits the loop. but, i don't know where to put it in the program. i'll give your suggestions a go and hope this will spark some insight.

OpenStudy (anonymous):

Sure thing. Let me know if you get stuck.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!