MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / solution

Function solution

project_euler/problem_007/sol2.py:52–102  ·  view source on GitHub ↗

Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 >>> solution(3.4) 5 >>> solution(0) Traceback (most recent call last): ..

(nth: int = 10001)

Source from the content-addressed store, hash-verified

50
51
52def solution(nth: int = 10001) -> int:
53 """
54 Returns the n-th prime number.
55
56 >>> solution(6)
57 13
58 >>> solution(1)
59 2
60 >>> solution(3)
61 5
62 >>> solution(20)
63 71
64 >>> solution(50)
65 229
66 >>> solution(100)
67 541
68 >>> solution(3.4)
69 5
70 >>> solution(0)
71 Traceback (most recent call last):
72 ...
73 ValueError: Parameter nth must be greater than or equal to one.
74 >>> solution(-17)
75 Traceback (most recent call last):
76 ...
77 ValueError: Parameter nth must be greater than or equal to one.
78 >>> solution([])
79 Traceback (most recent call last):
80 ...
81 TypeError: Parameter nth must be int or castable to int.
82 >>> solution("asd")
83 Traceback (most recent call last):
84 ...
85 TypeError: Parameter nth must be int or castable to int.
86 """
87
88 try:
89 nth = int(nth)
90 except TypeError, ValueError:
91 raise TypeError("Parameter nth must be int or castable to int.") from None
92 if nth <= 0:
93 raise ValueError("Parameter nth must be greater than or equal to one.")
94 primes: list[int] = []
95 num = 2
96 while len(primes) < nth:
97 if is_prime(num):
98 primes.append(num)
99 num += 1
100 else:
101 num += 1
102 return primes[len(primes) - 1]
103
104
105if __name__ == "__main__":

Callers 1

sol2.pyFile · 0.70

Calls 2

is_primeFunction · 0.70
appendMethod · 0.45

Tested by

no test coverage detected