romaklimenko
8/1/2017 - 6:28 PM

returns a random prime number

returns a random prime number

from random import randint

def is_prime(x):
    if x < 0:
        raise Exception("ne mogu negatives")

    if x == 0:
        raise Exception("ya ne znayu")

    if x == 1 or x == 2:
        return True

    if x % 2 == 0:
        return False

    max_divider = x ** 0.5

    divider = 3

    while divider <= max_divider:
        if x % divider == 0:
            return False
        divider += 2

    return True


def random_prime():
    max = 2 ** (4 * 8) / 2
    r = randint(1, max)

    if r != 2 and r % 2 == 0:
        r += 1

    if is_prime(r):
        return r

    low_r = r
    high_r = r

    count = 1000

    while True:
        if low_r > 3:
            low_r -= 2
            if is_prime(low_r):
                return low_r

        if high_r < max:
            high_r += 2
            if is_prime(high_r):
                return high_r

        count -= 1
        if count == 0:
            raise Exception("ya ustal ya uxozhu")


print(random_prime())