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

Function solution

project_euler/problem_003/sol2.py:15–60  ·  view source on GitHub ↗

Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equ

(n: int = 600851475143)

Source from the content-addressed store, hash-verified

13
14
15def solution(n: int = 600851475143) -> int:
16 """
17 Returns the largest prime factor of a given number n.
18
19 >>> solution(13195)
20 29
21 >>> solution(10)
22 5
23 >>> solution(17)
24 17
25 >>> solution(3.4)
26 3
27 >>> solution(0)
28 Traceback (most recent call last):
29 ...
30 ValueError: Parameter n must be greater than or equal to one.
31 >>> solution(-17)
32 Traceback (most recent call last):
33 ...
34 ValueError: Parameter n must be greater than or equal to one.
35 >>> solution([])
36 Traceback (most recent call last):
37 ...
38 TypeError: Parameter n must be int or castable to int.
39 >>> solution("asd")
40 Traceback (most recent call last):
41 ...
42 TypeError: Parameter n must be int or castable to int.
43 """
44
45 try:
46 n = int(n)
47 except TypeError, ValueError:
48 raise TypeError("Parameter n must be int or castable to int.")
49 if n <= 0:
50 raise ValueError("Parameter n must be greater than or equal to one.")
51 prime = 1
52 i = 2
53 while i * i <= n:
54 while n % i == 0:
55 prime = i
56 n //= i
57 i += 1
58 if n > 1:
59 prime = n
60 return int(prime)
61
62
63if __name__ == "__main__":

Callers 1

sol2.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected