예제 #1
0
파일: awful.py 프로젝트: cesarfm/pyprimes
def primes3():
    """Generate prime numbers by trial division slowly.

    >>> p = primes3()
    >>> [next(p) for _ in range(10)]
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

    This is an incremental improvement over ``primes2`` by only testing
    potential factors up to the square root of the candidate. For small
    primes below 50000 or so, this may be slightly faster than ``primes4``.

    """
    yield 2
    i = 3
    yield i
    while True:
        i += 2
        if all(i%p != 0 for p in range(3, isqrt(i)+1, 2)):
            yield i
예제 #2
0
파일: awful.py 프로젝트: cesarfm/pyprimes
def isprime(n):
    """Naive primality test using naive and unoptimized trial division.

    >>> isprime(17)
    True
    >>> isprime(18)
    False

    Naive, slow but thorough test for primality using unoptimized trial
    division. This function does far too much work, and consequently is
    very slow. Nevertheless, it is guaranteed to give the right answer.
    Eventually.
    """
    if n == 2:
        return True
    if n < 2 or n % 2 == 0:
        return False
    for i in range(3, isqrt(n)+1, 2):
        if n % i == 0:
            return False
    return True