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)
| 49 | |
| 50 | |
| 51 | def solution(n: int = 600851475143) -> int: |
| 52 | """ |
| 53 | Returns the largest prime factor of a given number n. |
| 54 | |
| 55 | >>> solution(13195) |
| 56 | 29 |
| 57 | >>> solution(10) |
| 58 | 5 |
| 59 | >>> solution(17) |
| 60 | 17 |
| 61 | >>> solution(3.4) |
| 62 | 3 |
| 63 | >>> solution(0) |
| 64 | Traceback (most recent call last): |
| 65 | ... |
| 66 | ValueError: Parameter n must be greater than or equal to one. |
| 67 | >>> solution(-17) |
| 68 | Traceback (most recent call last): |
| 69 | ... |
| 70 | ValueError: Parameter n must be greater than or equal to one. |
| 71 | >>> solution([]) |
| 72 | Traceback (most recent call last): |
| 73 | ... |
| 74 | TypeError: Parameter n must be int or castable to int. |
| 75 | >>> solution("asd") |
| 76 | Traceback (most recent call last): |
| 77 | ... |
| 78 | TypeError: Parameter n must be int or castable to int. |
| 79 | """ |
| 80 | |
| 81 | try: |
| 82 | n = int(n) |
| 83 | except TypeError, ValueError: |
| 84 | raise TypeError("Parameter n must be int or castable to int.") |
| 85 | if n <= 0: |
| 86 | raise ValueError("Parameter n must be greater than or equal to one.") |
| 87 | max_number = 0 |
| 88 | if is_prime(n): |
| 89 | return n |
| 90 | while n % 2 == 0: |
| 91 | n //= 2 |
| 92 | if is_prime(n): |
| 93 | return n |
| 94 | for i in range(3, int(math.sqrt(n)) + 1, 2): |
| 95 | if n % i == 0: |
| 96 | if is_prime(n // i): |
| 97 | max_number = n // i |
| 98 | break |
| 99 | elif is_prime(i): |
| 100 | max_number = i |
| 101 | return max_number |
| 102 | |
| 103 | |
| 104 | if __name__ == "__main__": |