Skip to content

Commit 4558e59

Browse files
committed
Add sol3 for project_euler proble_03
1 parent 76f5287 commit 4558e59

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

project_euler/problem_03/sol3.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
Problem:
3+
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor
4+
of a given number N?
5+
6+
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
7+
"""
8+
9+
10+
def solution(n):
11+
"""Returns the largest prime factor of a given number n.
12+
13+
>>> solution(13195)
14+
29
15+
>>> solution(10)
16+
5
17+
>>> solution(17)
18+
17
19+
>>> solution(3.4)
20+
3
21+
>>> solution(0)
22+
Traceback (most recent call last):
23+
...
24+
ValueError: Parameter n must be greater or equal to one.
25+
>>> solution(-17)
26+
Traceback (most recent call last):
27+
...
28+
ValueError: Parameter n must be greater or equal to one.
29+
>>> solution([])
30+
Traceback (most recent call last):
31+
...
32+
TypeError: Parameter n must be int or passive of cast to int.
33+
>>> solution("asd")
34+
Traceback (most recent call last):
35+
...
36+
TypeError: Parameter n must be int or passive of cast to int.
37+
"""
38+
try:
39+
n = int(n)
40+
except (TypeError, ValueError) as e:
41+
raise TypeError("Parameter n must be int or passive of cast to int.")
42+
if n <= 0:
43+
raise ValueError("Parameter n must be greater or equal to one.")
44+
prime = 1
45+
i = 2
46+
ans = 0
47+
if n==2:
48+
return 2
49+
while n > 2:
50+
while n%i != 0:
51+
i += 1
52+
ans = i
53+
while(n%i ==0):
54+
n = n/i
55+
i += 1
56+
57+
return int(ans)
58+
59+
60+
if __name__ == "__main__":
61+
#print(solution(int(input().strip())))
62+
import doctest
63+
doctest.testmod()

0 commit comments

Comments
 (0)