Ask Your Question

next prime number

asked 2018-10-21 02:30:05 +0200

bond_azoozbond gravatar image

updated 2018-10-21 13:12:42 +0200

slelievre gravatar image

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.'

See this code in SageCell.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2018-10-21 13:20:05 +0200

slelievre gravatar image

Some comments:

  • 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()
    sage: next_prime(12)
  • 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

edit flag offensive delete link more

answered 2018-10-21 18:23:05 +0200

dazedANDconfused gravatar image

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:

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.

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

1 follower


Asked: 2018-10-21 02:29:01 +0200

Seen: 2,407 times

Last updated: Oct 21 '18