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

@@ -25,32 +25,46 @@ After that, bruteforce all passed candidates sequences using
The bruteforce of this solution will be about 1 sec.
"""
import math
from itertools import permutations
from math import floor, sqrt
def is_prime(number: int) -> bool:
"""
function to check whether the number is prime or not.
>>> is_prime(2)
True
>>> is_prime(6)
"""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(-800)
False
>>> is_prime(104729)
>>> 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 < 2:
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(2, floor(sqrt(number)) + 1):
if number % i == 0:
# 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