I am trying to learn Python programming, and I'm pretty new at this.
I was having issues in printing a series of prime numbers from one to hundred. I can't figure our what's wrong with my code.
Here's what I wrote; it prints all the odd numbers instead of primes:
for num in range(1,101):
for i in range(2,num):
if (num%i==0):
break
else:
print(num)
break
First we find factor of that number
Script to check prime or not
Script to print all prime number upto n
The best way to solve the above problem would be to use the "Miller Rabin Primality Test" algorithm. It uses a probabilistic approach to find if a number is prime or not. And it is by-far the most efficient algorithm I've come across for the same.
The python implementation of the same is demonstrated below:
A Python Program function module that returns the 1'st N prime numbers:
You need to check all numbers from 2 to n-1 (to sqrt(n) actually, but ok, let it be n). If
n
is divisible by any of the numbers, it is not prime. If a number is prime, print it.You can write the same much shorter and more pythonic:
As I've said already, it would be better to check divisors not from 2 to n-1, but from 2 to sqrt(n):
For small numbers like 101 it doesn't matter, but for 10**8 the difference will be really big.
You can improve it a little more by incrementing the range you check by 2, and thereby only checking odd numbers. Like so:
Edited:
Print n prime numbers using python:
The fastest & best implementation of omitting primes: