# Plot with prime numbers

I am trying to create a visualization of how common it is for a number to be prime. I am fairly new with the program and was hoping to get some assistant with any veteran users. My code I wrote is:

def com_primes(k):
prime_list = []
for n in range(1,k+1):
for m in range(1,n+1):
if Integer(n)/Integer(n) & Integer(n)/1 in ZZ:
if is_prime(m):
prime_list.append((n,m))
return point(prime_divisor_list)


but the code is obviously wrong. If anyone could help me, that would be much appreciated.

edit retag close merge delete

Sort by ยป oldest newest most voted

Sage is useful because there are many ready-to-use tools. In particular to know if an integer is prime or to get its list of divisors.

sage: P1 = []   # list of pairs (n,n) when n is prime
sage: P2 = []   # list of pairs (n,d) where d|n and n is not prime
sage: for n in xsrange(1,100):
....:    if n.is_prime():
....:        P1.append((n,n))
....:    else:
....:        P2.extend([(n,d) for d in n.divisors()[1:]])
sage: G1 = point2d(P1,color='red',pointsize=20)
sage: G2 = point2d(P2,color='blue',pointsize=5)
sage: (G1 + G2).show()


Note that I used xsrange instead of xrange. This is because xsrange produces Sage integers from which you can use .is_prime() and .divisors() whereas xrange produces Python integers.

Concerning your problem "how common it is for a number to be prime" you may have a look at the prime number theorem which describes the distribution of primes among the integers.

more

Line 5: Integer(n)/Integer(n) should probably have Integer(m) in the denominator.

Line 5: replace & with in ZZ and. Actually, Integer(n)/1 will always be in ZZ. Maybe you should just have if Integer(n)/Integer(m) in ZZ: or if Integer(m).divides(n): but I'm not quite sure what you're looking for.

Last line: replace prime_divisor_list with prime_list.

Last line: should be indented four spaces.

So:

def com_primes(k):
prime_list = []
for n in range(1,k+1):
for m in range(1,n+1):
if Integer(m).divides(n):
if is_prime(m):
prime_list.append((n,m))
return point(prime_list)

more