# next prime number

Hi, I wrote code to find the next prime number. It works only if I put the number on the code. However I'm trying to find a way to have a range of numbers that the user can pick from. Here is the code:

num = (sage_input('Please enter test integer > 2: ')
# num =120
def is_prime(num):
for i in range(2,num):
if (num % i) == 0:
return False
return True

num = num + 1
while is_prime(num) == False:
num = num + 1
print num, 'is your next prime.'

edit retag close merge delete

Sort by » oldest newest most voted

• Parentheses are not balanced in the first line of code in the question. Remove an extraneous opening parenthesis (or add a closing parenthesis).

• The Python built-in function input can be used to ask for user input. This function does not work in SageCell.

• The function sage_input is very different. It helps finding what Sage input would give some object. See the documentation for sage_input.

• Sage has a built-in function for finding the next prime.

sage: 12.next_prime()
13
sage: next_prime(12)
13

• Sage has a function for listing primes in a given range.

sage: prime_range(12, 30)
[13, 17, 19, 23, 29]

• You can use "interacts" in Sage, see https://wiki.sagemath.org/interact.

more

Here is a possible implementation of what you are trying to accomplish using a Sage interact and the prime_range function that slelievre mentions in their answer:

@interact
def FindPrimes(start=1, end=100):
PrimeList = prime_range(start, end)
print "There are ", len(PrimeList), " primes between ", start, " and ", end
print "The next prime after start is ", next_prime(start)
print "The primes between ", start, " and ", end, " are: "
for i in range(0,len(PrimeList)):
print PrimeList[i]


Copy and paste the code into a Sage Cell Server. Press Evaluate. To change the start value the user can go to the input cell, type, for example, 35, and press enter. The Sage Interact then updates the results.

more