Check the Number is a Prime Number

From Software Engineers Wiki
Jump to: navigation, search

Write a program that checks whether the given number is a prime number.

Answer

import sys

def checkPrime(num):
        if (num < 2):
                return False
        if (num == 2):
                return True
        for i in range(2, num / 2 + 1):
                if num % i == 0:
                        return False
        return True

def primeTest():
        knownPrimeUntil100 = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }

        for i in range(2, 101):
                isPrimeFromFunc = checkPrime(i)
                isPrimeInList = i in knownPrimeUntil100
                if isPrimeFromFunc != isPrimeInList:
                        return False

        return True

def main():
        if (len(sys.argv) <= 1):
                print("Please provide number")
                sys.exit(1)

        num = int(sys.argv[1])
        isPrime = checkPrime(num)
        print("{} is {}a prime number".format(num, "not " if not isPrime else ""))

print("Prime Test {}".format("Passed" if primeTest() else "Failed"))
main()
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox