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).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |