-3

Write a function that accepts a positive integer n as function parameter and returns True if n is a prime number, False otherwise. Note that zero and one are not prime numbers and two is the only prime number that is even.

def prime_number (number):
    if (number > 1):
        if (number == 2):
            return (True)
        else:
            for item in range (2, number):
                if (number % item == 0):
                   return (False)
                else:
                   return (True)
    else:
        return (False)

#Main program
number = int(input("Enter a positive integer number: "))
result = prime_number(number)
print (result)

This is my code for finding prime numbers. However, there's a problem with this code that when I enter number as 9 it gives me output as True. 9 is not a prime number so it should output as False rather than True

Karan Thakkar
  • 1,007
  • 5
  • 24
  • 41
  • 1
    Please check similar questions already posted like [link] (http://stackoverflow.com/a/1801446/2599266) – Obsidian Feb 12 '16 at 07:33
  • If you search the internet, you'll find a lot of prime number search/verification implementations, including code written in Python, and even here on StackOverflow. You may want to start researching that path. –  Feb 12 '16 at 07:33
  • So as soon as you find a value that doesn't divide the number, you immediately return `True`? Does that sound right? 2 doesn't divide 9, but that doesn't make 9 prime does it? – Tom Karzes Feb 12 '16 at 07:33

3 Answers3

1

Recommendations for finding primes in this manner:

1) Handle 2, less than 2 and all even numbers as special cases, not as part of your test loop.

2) Try to divide the target number by all the odd numbers from 3 to the square root of the target number.

As far as your code:

1) nothing should follow a return() statement at the same level of indentation, so toss your 'break' statement.

2) you don't need to put things in parens to return them

3) get rid of your innermost 'else' clause, it's incorrect -- you should only return True if you get through the entire 'for' loop without returning False. Move this return statement to after the loop.

cdlane
  • 40,441
  • 5
  • 32
  • 81
1

It's known that all prime numbers (larger than 3) can be expressed as:

6k +/- 1 for some integer k

If you iterate over numbers of that form only it should make your algorithm more efficient.

Forge
  • 6,538
  • 6
  • 44
  • 64
-5
def prime_number (number):
if(number == 2):return True
if (number > 2):
    for item in range (2, number/2 +1):
        if (number % item == 0):
           return False

    return True



#Main program
number = int(raw_input("Enter a positive integer number: "))
result = prime_number(number)
print (result)

This solves your problem.

For efficiency you could look at sieve of erasthoreses.