Today we had a task where we had to plot the number of primes less than or equal to a given number x, against x. Here’s a method which plots the graph for x = 10,000 instantaneously.
First, look at this table.
x |
n = number of primes less than or equal to x |
2 |
1 |
3 |
2 |
4 |
2 |
5 |
3 |
6 |
3 |
7 |
4 |
8 |
4 |
9 |
4 |
10 |
4 |
11 |
5 |
12 |
5 |
13 |
6 |
14 |
6 |
15 |
6 |
16 |
6 |
17 |
7 |
18 |
7 |
19 |
8 |
20 |
8 |
Notice anything? n increases only if the next value of x happens to be a prime.
So if n = 6 for x = 15, n will remain 6 for x = 16 because 16 is not a prime.
But n will increase by 1 for x = 17 because 17 is a prime.
So we need not define a function which checks for the number of primes less than or equal to an integer, and use that function in each iteration of the loop. We can simply add 1 whenever we encounter a prime, and append that value to a list. If the next number is not a prime, simply append the current value. We are storing these in a list because we want to use it to plot a graph.
def generateListForCountingPrimes(n):
# The first element of the list l is the number of primes <= 2, the second element is the
# number of primes <= 3 and so on
l = [1]
i = 3
while i <= n:
# Where prime(k) is a function which checks for primality
if prime(i):
l.append(l[-1] + 1)
else:
l.append(l[-1])
i += 1
return l
import numpy as np
import matplotlib.pyplot as pp
x = np.arange(2, 500001, 1)
y1 = generateListForCountingPrimes(500000)
y2 = [(i*1.0)/np.log(i) for i in x]
pp.plot(x, y1, x, y2)
pp.show()