# How to use prime_range with a formula instead of an integer

Hi. First post here, so please tell me if I'm not doing this right. Thanks.

I want to find all the primes in a range defined by a formula rather than an integer. I tried:

1. a=n^2+1
2. b=(n+1)^2-1
3. 0 is less than n is less than 21 (I tried typing this here in help with just the symbols, but the preview only showed "0" if I did that.)
4. prime_range(a,b)

and got the error message:

TypeError                                 Traceback (most recent call last)
<ipython-input-1-9910057c7272> in <module>
----> 1 a=n**Integer(2)+Integer(1)
2 b=(n+Integer(1))**Integer(2)-Integer(1)
3 Integer(0)<n<Integer(20)
4 prime_range(a,b)
/home/sc_serv/sage/local/lib/python3.9/site-packages/sage/rings/integer.pyx in sage.rings.integer.Integer.__pow__ (build/cythonized/sage/rings/integer.c:15218)()
2206             return coercion_model.bin_op(left, right, operator.pow)
2207         # left is a non-Element: do the powering with a Python int
-> 2208         return left ** int(right)
2209
2210     cpdef _pow_(self, other):
TypeError: unsupported operand type(s) for ** or pow(): 'function' and 'int'


Can you tell me how to get the result I am looking for? Thank you!

edit retag close merge delete

Sort by » oldest newest most voted

The prime_range function accepts only numbers as arguments, not symbolic expressions.

Depending on your intended use of these prime ranges, that might be enough.

For instance, to count the number of primes in each such range:

for n in range(1, 21):
a = n^2 + 1
b = (n + 1)^2 + 1
nprimes = sum(1 for p in prime_range(a, b))
print(f"n = {n}: {nprimes} primes")


The output is:

n = 1: 2 primes
n = 2: 2 primes
n = 3: 2 primes
n = 4: 3 primes
n = 5: 2 primes
...
n = 16: 7 primes
n = 17: 5 primes
n = 18: 6 primes
n = 19: 6 primes
n = 20: 7 primes


The prime counting function prime_pi gives another way to get that count:

def primes_between_squares(n):
r"""
Return the number of squares between n^2 and (n+1)^2.
"""
return prime_pi((n+1)^2) - prime_pi(n^2)

for n in range(1, 21):
print(f"n = {n}: {primes_between_squares(n)} primes")


(same output).

more

Thank you! Counting the number of primes was going to be what I was going to work on next, and assuming I couldn't work it out, you've answered two questions for me. :) I really appreciate it.

( 2021-06-17 03:11:27 +0200 )edit