Last active
May 13, 2019 16:23
-
-
Save OussaZaki/128aa3d6919598769b64a5e910cb04bc to your computer and use it in GitHub Desktop.
Refined Eratosthenes sieve factorisation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python3 | |
import math | |
def max_prime_factor(n): | |
maxPrime = -1 | |
# We keep dividing n by 2 to get rid of all the even composite factors. | |
while n % 2 == 0: | |
maxPrime = 2 | |
n >>= 1 # equivalent to n //= 2 | |
# We loop over the possible odd factors. | |
# to remove the rest of the composites, and updating maxPrime to the largest factor. | |
for i in range(3, int(math.sqrt(n)) + 1, 2): | |
while n % i == 0: | |
maxPrime = i | |
n //= i | |
# If at this stage n is is still bigger than 2 | |
# then n must be prime so we return it, otherwise we return maxPrime | |
return n if n > 2 else maxPrime | |
T = int(input().strip()) | |
for _ in range(T): | |
N = int(input().strip()) | |
print(max_prime_factor(N)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment