Please have mercy on this complete idiot - I'm trying to do problem set 1 and am utterly stumped. I know very little about computers and nothing about Python except what the lectures and a bit of casual browsing have taught me. Here's my code: primeCount = 1 currentPrime = 1 while(primeCount<1000): currentPrime = currentPrime + 2 primeTester = currentPrime - 1 while(primeTester>1): primeResult = currentPrime%primeTester if primeResult == 0: if primeTester == 1: primeCount = primeCount + 1 else: primeTester = prim
Might be best to break down the problem. What criteria do we need to determine prime? *If 2 then it's prime *If it's even it's NOT prime *If it has a divisor it's NOT prime Let's start with the divisor condition. We can get that with a for: for: loop. example: for x in range (2,10): for i in range (2,x): print 'x=', x print 'i=', i This will take x and run i through range x. In essence x=5, then i range 2,3,4. If x=6, then i range 2,3,4,5. So now we need our conditionals: *If 2 then it's prime if x==2: *If it has a divisor it's NOT prime elif x%i==0: *If it's even it's NOT prime elif (x/2)*2==x: If all conditions above are met then print or return it as prime.
If you're still stumped you can look below for a starting point. I left print statements to help. It's important to have break statements when a condition is met (...if we fine that 6 is divisible by 2...we don't need to do 6/3,6/4,6/5). for x in range (2,10): for i in range (2,x): print 'x=', x print 'i=', i if x==2: print 'x is 2' elif x%i==0: print x, 'is not prime' break elif (x/2)*2==x: print x, 'is even' break else: print x, 'is prime' This is just a starting point. Below are some questions to help refine this program. *Is is necessary to divide by everything up to x? *How can we set x so it's not limited by range? *How about a counter? *Can we simplify this by breaking it up to separate functions?
you need to read the readings and try the examples in the readings - you can't get it all from the lectures
Join our real-time social learning platform and learn together with your friends!