In problem set 1, I cannot figure out how to loop the steps till the 1000th prime and I cant figure out to test that it's prime too. I guess that is the entire problem set 1. I understand that to test a prime I need to ensure that a%(2, a-1) =/= 0. However, (2, a-1) is a list and i have no idea how to change it to a int. Can anyone enlightened me?
Okay, so the definition of a prime number is that it is only divisible by 1 and itself, right? And we know about the remainder operand, %. So what if you made a loop that took a candidate, you'll probably want to start at one if it's finding all prime numbers up to the 1000th, and calculated if there is no remainder for any divisors not including one or the number itself. Also, we don't have to go all the way to the number do we? If you're testing let's say 100, you don't need to go past 50 because any numbers after that will definitely not work. And at the end of the test, if no divisors were found other than 1 and the number itself, then it is a prime number and you can increment some variable by one as well as the candidate and move on to the next one. However, if it isn't a prime number and some other divisor is found, then you would just move onto the next number without increasing the variable that counts prime numbers. Does that make sense?
Also, there is no need for a list in this problem. The range method would work a lot better for trying all values in between two given numbers.
How this helps. https://docs.python.org/2/tutorial/controlflow.html#for-statements
One of the biggest tricks to making this assignment execute fast is to remember what you learned about factoring numbers in high school. Lists are indexed. You address one of the elements by it's index. So a list: foo = [ 2, 3 ] The 3 is addressed as: foo[ 1 ] # lists are zero indexed. The len() function will tell us the LENgth of what we pass to it, so: len( foo ) equals 2. If we want to check the primeness of 5, we could: bar = 5 for i in foo: if( bar % i == 0 ): break foo.append( bar )
Join our real-time social learning platform and learn together with your friends!