Return to site

List the prime numbers from 1 to 100

broken image
broken image

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.

broken image

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.

broken image

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).

broken image