Generating Prime Numbers

Prime Sieve or Sieve of Eratosthenes.

This idea of generating prime numbers was proposed by a Greek mathematician Eratosthenes. The algorithm beings by marking all numbers in an array as primes and subsequently crossing out all the multiples (non-primes).

What are prime numbers
A prime number ‘p’ is a natural number with only two factors, 1 and the number itself i.e p. i.e A prime number cannot be factorized into more than 2 natural numbers.
Example: 2, 3, 5, 7, 9,…

Properties of prime numbers

  • All prime numbers are odd except 2.
  • All prime numbers except 2 and 3 are of the form 6*n+1 or 6*n-1.
    Example: 31 = 65+1
    Example: 941 = 6
    157-1
  • [Mersenne’s Primes] If a number of the form 2^n-1 is prime. Then ‘n’ has to be a prime, but not the other way around.
    Example: Number 31 is prime. It is of the form 2^5-1, then 5 has to be prime which it it.
    Example: Number 11 is prime. But that does not make 2^11-1 (2047) prime. 2047 is divisible by 23 and 89.

Example of generating primes using Prime Sieve or Sieve of Eratosthenes
Prime Sieve

Time Complexity of Prime Sieve Algorithm: O(N log log N))

Why is the time complexity of Prime Sieve Algorithm O(N log log N)

C++ : Prime Sieve algorithm implementation in C++11

Python : Prime Sieve algorithm implementation in Python3

#!/usr/bin/python3

import math

def GeneratePrimes (num_range) :

    # Mark all numbers as prime
    list_numbers = num_range * [True] 

    # Cross out 0, 1 as they are not primes
    list_numbers[0] = list_numbers[1] = False

    square_root = int(math.sqrt(num_range))

    for p in range(square_root) :
        if (list_numbers[p] == True) :
            for i in range (p*p, num_range, p) : 
                # Cross out non primes by marking them false
                list_numbers[i] = False

    print ("Primes upto "+str(num_range)+" :")
    for p in range(len(list_numbers)) :
        if(list_numbers[p] == True) :
           print (p, end = ' ')
    print("\n") 

GeneratePrimes(100)
GeneratePrimes(1000)

Output

Primes upto 100 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

Primes upto 1000 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 961 967 971 977 983 991 997 

Copyright (c) 2019-2020, Algotree.org.
All rights reserved.