How to Check if a Number is Prime in Python?

  • MHB
  • Thread starter Ackbach
  • Start date
  • Tags
    2015
In summary, there is a simple algorithm called the Sieve of Eratosthenes that can be used to determine if a positive integer is prime. Every positive integer can be classified as either prime or composite, with prime numbers only being divisible by 1 and themselves. 1 is not considered a prime number because it only has one factor. The most common way to prove a positive integer is prime is by using a proof by contradiction. The largest known prime number as of 2021 is 282,589,933-1, also known as M82589933.
  • #1
Ackbach
Gold Member
MHB
4,155
92
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
  • #2
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)
#
 

FAQ: How to Check if a Number is Prime in Python?

Is there a simple way to determine if a positive integer is prime?

Yes, there is a simple algorithm called the Sieve of Eratosthenes that can be used to determine if a positive integer is prime. It involves creating a list of all numbers from 2 to the given number and then crossing out all multiples of each number. The remaining numbers are prime. This method is efficient for smaller numbers, but may become more time-consuming for larger numbers.

Can all positive integers be classified as either prime or composite?

Yes, every positive integer can be classified as either prime or composite. A prime number is a positive integer that is only divisible by 1 and itself, while a composite number is a positive integer that has at least one other factor besides 1 and itself.

Is 1 considered a prime number?

No, 1 is not considered a prime number. This is because it only has one factor, which is 1. Prime numbers must have exactly two factors, 1 and itself.

How do you prove that a positive integer is prime?

The most common way to prove that a positive integer is prime is by using a proof by contradiction. This involves assuming that the number is not prime and then showing that this leads to a contradiction, thus proving that the number must be prime. Other methods of proof, such as using the Fundamental Theorem of Arithmetic or the Sieve of Eratosthenes, can also be used.

What is the largest known prime number?

As of 2021, the largest known prime number is 282,589,933-1, also known as M82589933. This number has 24,862,048 digits and was discovered in December 2018 by the Great Internet Mersenne Prime Search (GIMPS) project.

Similar threads

Replies
1
Views
2K
Replies
1
Views
2K
Replies
1
Views
1K
Replies
1
Views
2K
Replies
1
Views
1K
Replies
1
Views
1K
Replies
1
Views
2K
Replies
1
Views
1K
Back
Top