I am having problems with PS1 (calculating the 1000th prime). I am a complete noob to Python, I understand the basics so far, I just can't get it right. http://dpaste.com/549082/ I know there are key elements I am just leaving out of my code, so if someone could just point some of the things out that I need to do to get the 1000th prime (and perhaps point me to some other examples of working code for this problem) I would really appreciate it. (I wanted a program that would print all prime numbers up to 1000, not just the 1000th prime)
Hoot! You just asked your first question! Hang tight while I find people to answer it for you. You can thank people who give you good answers by clicking the 'Good Answer' button on the right!
Your program prints every odd number up 2001. it check to see if it is divisible by 2, and when it is not, it prints, adds to tally, changes the 'prime' value to check the next number. Not at all a bad program if you want to print odds. But you don't want every odd number, you want every prime. A prime number is divisible by itself and one only. The idea is to get a test number, walk through each possible divisor to find whether it is a prime, and have a way to count primes (and print if that's what you want.). to walk through a bunch of possibles, you will want a loop. When I did this question, I first tried writing a program that can worked out if a given number is a prime, and then added to it the extra stuff.
I can write a code that find prime. Now I am having trouble getting it to print all primes up to 1000. http://dpaste.com/549369/ What am I missing? Is it in line five?
Well, you don't want to be increasing num every time it runs through a divisor. x changes, num shouldn't. In your for loop, you want to test 1 number to see if it has any divisors. Once it has ran through, then you want to change num to test a new number. When you think of the loop this way, then you see that every time it doesn't find a divisor, that doesn't mean it is a prime. It is a prime if it can get through the whole loop without finding a divisor (or 1 divisor if it checks itself%itself) Make sure when you are testing your programs as you go, you check for both numbers you know will work and numbers you know won't. Also, add in print lines, so you see if the program is outputting what you expect. I played with your program and took out everything except the 'is it a prime' part and added print lines. I have posted it http://dpaste.com/549421/ I hope it is able to illustrate what is going on in your program and how to test. Run it.
http://www.mathsisfun.com/prime_numbers.html this is a list of the primes up to 1000
If you want to see what happens with your num increasing every loop, just uncomment it in my test run, re-indent it, and add a print line to show it.
Join our real-time social learning platform and learn together with your friends!