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
SUMMARY

This discussion focuses on creating a Python program to check if a positive integer is prime without using built-in functions like "IsPrime(n)". The solution involves checking all numbers up to the square root of the input integer, skipping even numbers after 2. The program must handle input validation, returning a boolean indicating primality and an error message if the input is invalid. The implementation is designed to run correctly with Python Version 3.4.

PREREQUISITES
  • Understanding of Python programming, specifically version 3.4
  • Knowledge of basic number theory, particularly prime numbers
  • Familiarity with input validation techniques in programming
  • Experience with defining classes and returning multiple values in Python
NEXT STEPS
  • Research how to implement input validation in Python
  • Learn about the mathematical concept of prime numbers and their properties
  • Explore Python's class structure and how to return multiple outputs
  • Investigate optimization techniques for primality testing algorithms
USEFUL FOR

This discussion is beneficial for Python developers, computer science students, and anyone interested in algorithm design and number theory, particularly in the context of primality testing.

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
5K
  • · Replies 1 ·
Replies
1
Views
1K
  • · 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
2K