2019-11-07 08:37:28 +00:00
|
|
|
"""
|
2020-10-25 03:23:16 +00:00
|
|
|
Project Euler Problem 3: https://projecteuler.net/problem=3
|
2019-11-07 08:37:28 +00:00
|
|
|
|
2020-10-25 03:23:16 +00:00
|
|
|
Largest prime factor
|
|
|
|
|
|
|
|
The prime factors of 13195 are 5, 7, 13 and 29.
|
|
|
|
|
|
|
|
What is the largest prime factor of the number 600851475143?
|
|
|
|
|
|
|
|
References:
|
|
|
|
- https://en.wikipedia.org/wiki/Prime_number#Unique_factorization
|
2019-11-07 08:37:28 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
2020-10-06 14:54:39 +00:00
|
|
|
def solution(n: int = 600851475143) -> int:
|
2020-10-25 03:23:16 +00:00
|
|
|
"""
|
|
|
|
Returns the largest prime factor of a given number n.
|
|
|
|
|
2019-11-07 08:37:28 +00:00
|
|
|
>>> solution(13195)
|
|
|
|
29
|
|
|
|
>>> solution(10)
|
|
|
|
5
|
|
|
|
>>> solution(17)
|
|
|
|
17
|
|
|
|
>>> solution(3.4)
|
|
|
|
3
|
|
|
|
>>> solution(0)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2020-10-25 03:23:16 +00:00
|
|
|
ValueError: Parameter n must be greater than or equal to one.
|
2019-11-07 08:37:28 +00:00
|
|
|
>>> solution(-17)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2020-10-25 03:23:16 +00:00
|
|
|
ValueError: Parameter n must be greater than or equal to one.
|
2019-11-07 08:37:28 +00:00
|
|
|
>>> solution([])
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2020-10-25 03:23:16 +00:00
|
|
|
TypeError: Parameter n must be int or castable to int.
|
2019-11-07 08:37:28 +00:00
|
|
|
>>> solution("asd")
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2020-10-25 03:23:16 +00:00
|
|
|
TypeError: Parameter n must be int or castable to int.
|
2019-11-07 08:37:28 +00:00
|
|
|
"""
|
2020-10-25 03:23:16 +00:00
|
|
|
|
2019-11-07 08:37:28 +00:00
|
|
|
try:
|
|
|
|
n = int(n)
|
|
|
|
except (TypeError, ValueError):
|
2020-10-25 03:23:16 +00:00
|
|
|
raise TypeError("Parameter n must be int or castable to int.")
|
2019-11-07 08:37:28 +00:00
|
|
|
if n <= 0:
|
2020-10-25 03:23:16 +00:00
|
|
|
raise ValueError("Parameter n must be greater than or equal to one.")
|
2019-11-07 08:37:28 +00:00
|
|
|
i = 2
|
|
|
|
ans = 0
|
|
|
|
if n == 2:
|
|
|
|
return 2
|
|
|
|
while n > 2:
|
|
|
|
while n % i != 0:
|
|
|
|
i += 1
|
|
|
|
ans = i
|
|
|
|
while n % i == 0:
|
2021-10-11 16:33:44 +00:00
|
|
|
n = n // i
|
2019-11-07 08:37:28 +00:00
|
|
|
i += 1
|
|
|
|
return int(ans)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2020-10-25 03:23:16 +00:00
|
|
|
print(f"{solution() = }")
|