Unify O(sqrt(N)) is_prime functions under project_euler (#6258)

* fixes #5434

* fixes broken solution

* removes assert

* removes assert

* Apply suggestions from code review

Co-authored-by: John Law <johnlaw.po@gmail.com>

* Update project_euler/problem_003/sol1.py

Co-authored-by: John Law <johnlaw.po@gmail.com>
This commit is contained in:
Nikos Giachoudis
2022-09-14 11:40:04 +03:00
committed by GitHub
parent 81e30fd33c
commit 2104fa7aeb
12 changed files with 313 additions and 135 deletions

View File

@@ -33,29 +33,46 @@ So we check individually each one of these before incrementing our
count of current primes.
"""
from math import isqrt
import math
def is_prime(number: int) -> int:
"""
Returns whether the given number is prime or not
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)
0
>>> is_prime(17)
1
>>> is_prime(10000)
0
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
"""
if number == 1:
return 0
if number % 2 == 0 and number > 2:
return 0
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
for i in range(3, isqrt(number) + 1, 2):
if number % i == 0:
return 0
return 1
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def solution(ratio: float = 0.1) -> int: