I'm doing some reading in a python book and am doing one of the chapter exercises but I cant figure out how to get it to work and was hoping some of you python guru's could help out?

Heres description of the problem to be solved:

"A positive whole number n > 2 is prime if no number between 2 and the square root of n (inclusive) evenly divides n. Write a program that accepts a value of n as input and determines if the value is prime. If n is not prime, your program should quit as soon as it finds a value that evenly divides n."

Heres the code I have so far but it doesnt work very good...

def main():

    import math

    print "This program determines if a number you enter is prime or not.\n"
    n = input ("Please enter a number greater than 1: ")

    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            print n, "is not a prime number"
        i += 1
    print n, "is a prime number!"

main()

It tells me if a number is prime, but if it isnt prime it tells me it isnt, then tells me it is! LOL. I'm still a newbie when it comes to python...

I was able to get this far, but as far as "quitting as soon as it finds a value that evenly divides n." I have no clue how to do that...

Could someone please help?

Thanks a million!

def main():

    import math

    print "This program determines if a number you enter is prime or not.\n"
    n = input ("Please enter a number greater than 1: ")

    n = abs(n)
    i = 2
    msg = "is a prime number!"
    while i <= math.sqrt(n):
        if n % i == 0:
            msg = "is not a prime number"
        i += 1
    print n, msg

main()

katharnakh.

You can also use a function. Also you calculate math.sqrt(n) on every while loop. Once is enough.

import math

def test_for_prime(n):
    n = abs(n)
    j = 2
    stop=math.sqrt(n):
    while j <= stop:
        if n % j == 0:
            return False
        j += 1
    return True

if __name__ == "__main__":
    print "This program determines if a number you enter is prime or not.\n"
    n_input = input ("Please enter a number greater than 1: ")

    result=test_for_prime(n_input)
    if result:
       print n_input, "Is prime"
    else:
       print n_input, "is Not prime"

    ##  or a shortcut
    if test_for_prime(n_input):
       print n_input, "Is prime"
    else:
       print n_input, "is Not prime"

If you want to speed this up you can test for if n % 2 == 0:, then start at 3 and increment the counter by two each time, skipping the even numbers.

This article has been dead for over six months. Start a new discussion instead.