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

Function solution

project_euler/problem_003/sol3.py:15–62  ·  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 i = 2
52 ans = 0
53 if n == 2:
54 return 2
55 while n > 2:
56 while n % i != 0:
57 i += 1
58 ans = i
59 while n % i == 0:
60 n = n // i
61 i += 1
62 return int(ans)
63
64
65if __name__ == "__main__":

Callers 1

sol3.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected