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

Hey, I just finished PS1 problem 1, and this is my code: from math import sqrt prime = 3 count = 1 while count<100: flag = 0 for i in range(3, int(sqrt(prime))+1): if prime%i == 0: flag = 1 break if flag == 0: count = count + 1 prime = prime + 2 print '100th prime: ',prime-2 Is this ok, or is there a better way to do it? Thank you!

OpenStudy (anonymous):

Oops, it's 1000th prime! Same program, with 1000 instead of 100.

OpenStudy (anonymous):

well u can shorten the code and get rid of the flag .. and my personal advice is to use tuple instead of the counter .. take a look here.. http://dpaste.com/hold/563189/

OpenStudy (anonymous):

I second sunu here. You'll see a big difference when you start working on the 2nd problem. If you do it with tuples, all you need to do is simply loop through the tuple, computing the member's log, and then compare it's total to n. A little note on your code though: count should start at 2, since 3 is the 2nd prime (2 being the first).

OpenStudy (anonymous):

Could you please explain what a "tuple" is? @Lifeburner: I'm pretty sure that my logic is sound, and count has to begin from 1 because 2 is the only prime that I'm not checking for! I suppose I should have added the comments :)

OpenStudy (anonymous):

Ah, sorry. Yes, you were doing < 1000 instead of < 1001, so you should set it to 1. Also, a tuple is like a list. Only it's immutable and the position of its members has semantic meaning. A list is mutable, and the position of its members are simply their ordering.

OpenStudy (anonymous):

please use dpaste.com - paste your code there. select Python for the syntax - then post the link here. thnx

OpenStudy (anonymous):

hey bwCA we should use htttp://ideone.com instead from now one...that is one damn good site

OpenStudy (anonymous):

@Lifeburner: I'll check it out! @bwCA: I didn't know, and I'll do it from now on

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!