MHB How to Check if a Number is Prime in Python?

  • Thread starter Thread starter Ackbach
  • Start date Start date
  • Tags Tags
    2015
Click For Summary
To check if a number is prime in Python, create a program that verifies a positive integer without using built-in functions like "IsPrime(n)". The algorithm should check divisibility for all integers up to the square root of the input number, skipping even numbers after checking for 2. The program must return a boolean indicating primality and an error message if the input is invalid. It should be structured to return multiple outputs by defining a class for the results. The solution must be compatible with Python Version 3.4.
Ackbach
Gold Member
MHB
Messages
4,148
Reaction score
94
Here is this week's POTW:

-----

Write a computer program in Python to check a positive integer for primality. You may not use any built-in primitives that look like "IsPrime(n)". Check all the numbers up to $\sqrt{n}$, and skip the evens after 2.

Inputs: integer n. Check that the input is a positive integer. If it is not an integer, return an informative error message.

Outputs: boolean IsPrime, string Error. The boolean will be TRUE if the integer is prime, and FALSE if it is not. The error string will be empty if the input is a positive integer, and will return a suitable error message if it is not.

NB: because the function must return multiple values, define a class containing all the outputs, and return that.

The program must run correctly with Python Version 3.4.

-----

Remember to read the http://www.mathhelpboards.com/showthread.php?772-Problem-of-the-Week-%28POTW%29-Procedure-and-Guidelines to find out how to http://www.mathhelpboards.com/forms.php?do=form&fid=2!
 
Physics news on Phys.org
Congratulations to Bacterius for his correct (overliteral) solution, which I give below:

Code:
#!/usr/bin/env python3

# A primality test, following Ackbach's precise specifications.

class Result:
    def __init__(self, IsPrime, Error):
        self.IsPrime = IsPrime
        self.Error = Error

    @staticmethod
    def Error(msg):
        return Result(None, msg)

    @staticmethod
    def IsPrime():
        return Result(True, "")

    @staticmethod
    def IsNotPrime():
        return Result(False, "")

    def __repr__(self):
        return '(IsPrime={0}, Error="{1}")'.format(self.IsPrime,
                                                   self.Error)

def is_prime(n):
    if not isinstance(n, int):
        return Result.Error("an informative error message")

    if n <= 0:
        return Result.Error("a suitable error message")

    if n == 2:
        return Result.IsPrime()
    elif n == 1 or n % 2 == 0:
        return Result.IsNotPrime()
    else:
        divisor = 3

        while divisor * divisor <= n:
            if n % divisor == 0:
                return Result.IsNotPrime()
            else:
                divisor += 2

        return Result.IsPrime()

# PS: it isn't necessary to define a class to return multiple values in Python
#     as multiple return values are automatically packed into a tuple, e.g.:
#
#   def func():
#       return 12345, "hello"
#
#   x, y = func()
#   print(x)        (prints 12345)
#   print(y)        (prints hello)
#
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K