Search code examples
pythonprimes

Program to tell us which period of 100s between 100 to 10000 has the most prime numbers


I wanted to write a program to tell us which period of 100s (so which hundred category whether it'd be 100 to 200 or 200 to 300 and so on) between 100 to 10000 has the most prime numbers. I have no idea how to go at the problem and categorize the hundreds, I know how to tell how many primes are between two points but how do I iterate through 100 to 10000 while counting the primes between each hundred. Thank you for your time.


Solution

  • I wrote a very simple program that does what you asked, We iterate over the ranges 100-199, 200-299, and so on.. with each range we count the number of primes. each time we find more primes that our saved Maximum - we change that Maximum and save the range in which we found that many.

    Code:

    import math
    def is_prime(x):
        #for num in range(2, int(x**0.5) + 1):
        for num in range(2, int(math.sqrt(x)) + 1):
            if x % num == 0:
                return False
        return True
    
    def find_maximum_range_with_primes():
        max_range = None
        max_counter = 0
    
        # 10 ranges total: 100-200, 200-300, ...
        for j in range(1, 10):
            counter = 0
    
            # count primes in range
            for i in range(100*j ,100*(j+1)):
                
                if is_prime(i):
                    counter += 1
                    #print(i) 
    
            # if current range has more primes than the maximum found
            # set maximum to hole the counter, and save the range
            
            if counter > max_counter:
                max_counter = counter
                max_range = (100*j, 100*(j+1))
        return max_range
    
    print(find_maximum_range_with_primes())
                
    
    

    Now, this code is not optimized, so be aware there are ways to make that better, but for what you asked I believe it will serve its purpose.