Then you can remove if i max_div or x = i or x = i2): doesn't need those extra parentheses: if x > max_div or x = i or x = i2: is valid. since you know that a prime pair can't start with 1 or 2. If you want to mostly stick to your current code but improve details: My sieve-based code above is four times faster than your original code and 15% smaller. Don't trust any answer until you've fully tested it. His second answer takes three times longer than your original code. The first answer provided by takes twice as long as your original code to count the pairs up to one million. For timing purposes, we'll count, rather than print, pairs. Let's consider 1000000 (a million) instead.
When working with primes up to 100, any code will do, it's too small a range to tax performance.
Here's sieve-based approach that's a little shorter and a lot faster: def find_prime_pairs(n):įor number in range(2, int(n ** 0.5) + 1):įor index in range(number * number, n, number): How can i optimize my code to make it shorter and faster ?