Skip to content

Instantly share code, notes, and snippets.

@mdamircoder
Last active February 3, 2018 10:38
Show Gist options
  • Save mdamircoder/14ec8b909aa8cbba75991b84d0289501 to your computer and use it in GitHub Desktop.
Save mdamircoder/14ec8b909aa8cbba75991b84d0289501 to your computer and use it in GitHub Desktop.
Find Largest / Maximum Prime Divisor in Python
def Max_Prime_Divisor(n):
PrDiv = -1
if n == 1 : return "N.A." # 1 is handled separately
# All primes are odd numbers except 2
# We will first check for 2
# Then for other odd numbers starting from 3, same procedure
while n % 2 == 0:
PrDiv = 2
n = n//2
upto = int(n**0.5) + 1 # math.sqrt(n) + 1
for odd in range( 3, upto, 2 ):
while n % odd == 0:
# Make sure no multiples of prime, enter here
PrDiv = odd
n = n//odd
PrDiv = max (n, PrDiv) # When n is prime itself
return PrDiv
#============================ INPUT SECTION ============================
n = 1564
print("Maximum prime divisor of", n, "is", Max_Prime_Divisor(n)) #23
n = 15
print("Maximum prime divisor of", n, "is", Max_Prime_Divisor(n)) #5
n = 89
print("Maximum prime divisor of", n, "is", Max_Prime_Divisor(n)) #89
n = 1
print("Maximum prime divisor of", n, "is", Max_Prime_Divisor(n)) #N.A.
# Source : https://github.com/mdamirsohail13/Algorithms/blob/master/Maximum-Prime-Divisor/Maximum-Prime-Divisor.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment