Ask Your Question

Plot with prime numbers

asked 2013-09-06 17:39:58 +0100

hee1 gravatar image

updated 2013-09-07 09:52:05 +0100

vdelecroix gravatar image

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):
return point(prime_divisor_list)

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

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2013-09-07 09:49:53 +0100

vdelecroix gravatar image

updated 2013-09-07 09:53:48 +0100

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.

edit flag offensive delete link more

answered 2013-09-06 23:15:03 +0100

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.


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):
    return point(prime_list)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2013-09-06 17:39:58 +0100

Seen: 1,248 times

Last updated: Sep 07 '13