
I think there is always room for improvement though. Also, it would probably be a bit more efficient to store the results to a file than verbose and could save a lot on memory if it was just one at a time but would cost a little bit more time due to disk writes. Otherwise I didn't edit much other then make the values get stored in and output array to be returned by the class. Thanks guys!!ĮDIT: Oh, and by the way, I didn't feel there was any need to import the math library for the square root of a value as the equivalent is just (n**.5). Notes: Solution 5 listed above (as proposed by user448810) turned out to be the fastest and honestly quiet creative and clever. Method 5 as described by user448810 (which I thought was quite clever): def primes_method5(n): Method 4 as described by Igor Chubin: def primes_method4(n): Method 3 as described by Igor Chubin: def primes_method3(n): If all(num % i != 0 for i in range(2, num)): Method 2 as described by Igor Chubin: def primes_method2(n): Method 1 as described by Igor Chubin: def primes_method1(n): So kudos to you, sir! In all examples I use a values of 1 million (1,000,000) as n. But I have to acknowledge for his clever solution, which turns out to be the fastest by far (of those I tested). Below are some modifications I did to create simple classes of examples by both and First off let me say it's all great information, thank you guys.

I'm a proponent of not assuming the best solution and testing it. Need to check with even numbers, so 'i' value can be start with 3 and Like so: import mathĪs in the first loop odd numbers are selected, in the second loop no You can improve it a little more by incrementing the range you check by 2, and thereby only checking odd numbers. If all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):įor small numbers like 101 it doesn't matter, but for 10**8 the difference will be really big.

You can write the same much shorter and more pythonic: for num in range(2,101):Īs I've said already, it would be better to check divisors not from 2 to n-1, but from 2 to sqrt(n): import math If n is divisible by any of the numbers, it is not prime. You need to check all numbers from 2 to n-1 (to sqrt(n) actually, but ok, let it be n).
