TheAlgorithms-Python
84 строки · 1.8 Кб
1"""
2Project Euler Problem 7: https://projecteuler.net/problem=7
3
410001st prime
5
6By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
7can see that the 6th prime is 13.
8
9What is the 10001st prime number?
10
11References:
12- https://en.wikipedia.org/wiki/Prime_number
13"""
14
15from math import sqrt
16
17
18def is_prime(number: int) -> bool:
19"""Checks to see if a number is a prime in O(sqrt(n)).
20A number is prime if it has exactly two factors: 1 and itself.
21Returns boolean representing primality of given number (i.e., if the
22result is true, then the number is indeed prime else it is not).
23
24>>> is_prime(2)
25True
26>>> is_prime(3)
27True
28>>> is_prime(27)
29False
30>>> is_prime(2999)
31True
32>>> is_prime(0)
33False
34>>> is_prime(1)
35False
36"""
37
38if 1 < number < 4:
39# 2 and 3 are primes
40return True
41elif number < 2 or number % 2 == 0 or number % 3 == 0:
42# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
43return False
44
45# All primes number are in format of 6k +/- 1
46for i in range(5, int(sqrt(number) + 1), 6):
47if number % i == 0 or number % (i + 2) == 0:
48return False
49return True
50
51
52def solution(nth: int = 10001) -> int:
53"""
54Returns the n-th prime number.
55
56>>> solution(6)
5713
58>>> solution(1)
592
60>>> solution(3)
615
62>>> solution(20)
6371
64>>> solution(50)
65229
66>>> solution(100)
67541
68"""
69
70count = 0
71number = 1
72while count != nth and number < 3:
73number += 1
74if is_prime(number):
75count += 1
76while count != nth:
77number += 2
78if is_prime(number):
79count += 1
80return number
81
82
83if __name__ == "__main__":
84print(f"{solution() = }")
85