1

i wrote this super simple python code to count the number of prime numbers up to some large value. The problem is for a value like 1e+8the program takes so much time, i want to improve this code for faster result and better performance. here's the code:

import math

def is_prime(num):
    if num%2 ==0 and num>2:
        return 0
    for i in range(3, int(math.sqrt(num)) + 1, 2):
        if num % i == 0:
            return 0
    return 1

def count_prime(num):
    ct=0;
    for i in range(2,num+1,1):
        if is_prime(i)==1:
            ct+=1
    return ct

1 Answers1

-1

As suggested in the comments, you could start improving your is_prime() function. Try other algorithms like the suggested sieve, or the Miller Rabin test. I implemented the latter during a cryptography seminar and it wasnt to hard. (Note: the algorithm is a probabilistic algorithm, but dont be bothered by that to much). This could leed to a better time complexity for your prime check.

After this you could maybe think about multiple runs of ur count_prime() function. Here you could store the values from your runs and start from this point on the next start.

Example:

  1. In the first run you calculate all primes for n = 5000. You get some result = x you store x for 5000.
  2. In the second run maybe you enter 10.000 as ur designated input. Now you dont need to start over from 2 again, but you can start with your stored result and continue calculation from 5001. The addition of the results then is your result for 10.000
ChrisN
  • 74
  • 3