mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-31 06:33:44 +00:00
4fe50bc1fc
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.8.6 → v0.9.1](https://github.com/astral-sh/ruff-pre-commit/compare/v0.8.6...v0.9.1) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update maths/dual_number_automatic_differentiation.py * Update maths/dual_number_automatic_differentiation.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update dual_number_automatic_differentiation.py * Update dual_number_automatic_differentiation.py * No <fin-streamer> tag with the specified data-test attribute found. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
60 lines
1.3 KiB
Python
60 lines
1.3 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
module to operations with prime numbers
|
|
"""
|
|
|
|
import math
|
|
|
|
|
|
def is_prime(number: int) -> bool:
|
|
"""Checks to see if a number is a prime in O(sqrt(n)).
|
|
|
|
A number is prime if it has exactly two factors: 1 and itself.
|
|
|
|
>>> is_prime(0)
|
|
False
|
|
>>> is_prime(1)
|
|
False
|
|
>>> is_prime(2)
|
|
True
|
|
>>> is_prime(3)
|
|
True
|
|
>>> is_prime(27)
|
|
False
|
|
>>> is_prime(87)
|
|
False
|
|
>>> is_prime(563)
|
|
True
|
|
>>> is_prime(2999)
|
|
True
|
|
>>> is_prime(67483)
|
|
False
|
|
"""
|
|
|
|
# precondition
|
|
assert isinstance(number, int) and (number >= 0), (
|
|
"'number' must been an int and positive"
|
|
)
|
|
|
|
if 1 < number < 4:
|
|
# 2 and 3 are primes
|
|
return True
|
|
elif number < 2 or not number % 2:
|
|
# Negatives, 0, 1 and all even numbers are not primes
|
|
return False
|
|
|
|
odd_numbers = range(3, int(math.sqrt(number) + 1), 2)
|
|
return not any(not number % i for i in odd_numbers)
|
|
|
|
|
|
def next_prime(value, factor=1, **kwargs):
|
|
value = factor * value
|
|
first_value_val = value
|
|
|
|
while not is_prime(value):
|
|
value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1
|
|
|
|
if value == first_value_val:
|
|
return next_prime(value + 1, **kwargs)
|
|
return value
|