Integer - Prime Number

About

A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.

All prime numbers are Integer - Parity (Even|Odd), with one exception: the prime number 2.

Python Function

Naive way

def is_prime(x):
    if x > 1:
        for i in range(2,x-1):
            if (x % i == 0):
                return False
    else:
        return False
    return True

Second

Python script that gives false positives when input is a Carmichael number (rare) and otherwise with probability 1/20

from random import randint
def is_prime(p, n=20): return all([pow(randint(1,p-1),p-1,p) == 1 for i in range(n)])

for i in range(2,10):
    print(i,is_prime(i))
2 True
3 True
4 False
5 True
6 False
7 True
8 False
9 False

Powered by ComboStrap