课程: Python Essential Training

Solution: Finding primes faster - Python教程

课程: Python Essential Training

Solution: Finding primes faster

- [Narrator] For this challenge, as you probably figured out, it helps to keep a list of prime numbers as you go along. Not only is this list the thing that gets returned at the end of the function, but we'll use it to check for factors of the number that we're currently testing. So here's our list of primes. I'll add a two in here to start. And the number two is an odd prime. Wait, let me rephrase that. The number two is a strange prime. It's the only even prime, which makes it odd. So starting with this value, this two in our list, will help our function calculate the rest of the primes up to the number we've been given. Then, for each number between three and the number we passed into the function, we're going to get the square root. Note that I'm putting this value into a variable. I could just put a number to the 0.5 power in there, but then we'd be recalculating it every time we go through that loop. So it saves a little bit of computing power just to store the result up here. If our number is divisible by the factor, so if the number modulus factor equals zero, then we know that it's not prime. It has a divisors, and we break. Else, if we've gone past the square root of the number and we haven't found any factors yet, we know that it's prime. So we can append that number to our list of primes. We found a new one. Awesome. Finally, we return the list of primes we've collected. Often in programming, you'll make a first pass at a problem and find a less than ideal solution, like with our first prime number program earlier in this chapter. Then you might have some insight or learn something that allows you to dramatically increase the efficiency of your code. So one time, I figured out how to write a program more efficiently as I was drifting off to sleep. I had to turn the lights on, code it up, and I stayed up way too late, but it was worth it. It took the runtime of my program down from two days to 15 minutes. I was so excited. Always be careful not to over-optimize your programs. You can write a pile of unreadable garbage while chasing some slight efficiency that doesn't even matter. Remember that happy middle ground? That sweet spot is the most Pythonic way.

内容