Find largest prime factor of a number | Python3 code to find largest prime factor of number ; A function to find largest prime factor ; Initialize the maximum prime factor variable with the lowest one ; Print the number of 2 s that divide n ; n must be odd at this point ; now we have to iterate only for integers who does not have prime factor 2 and 3 ; This condition is to handle the case when n is a prime number greater than 4 ; Driver code to test above function
import math NEW_LINE def maxPrimeFactors ( n ) : NEW_LINE INDENT maxPrime = - 1 NEW_LINE while n % 2 == 0 : NEW_LINE INDENT maxPrime = 2 NEW_LINE DEDENT while n % 3 == 0 : NEW_LINE INDENT maxPrime = 3 NEW_LINE n = n / 3 NEW_LINE DEDENT for i in range ( 5 , int ( math . sqrt ( n ) ) + 1 , 6 ) : NEW_LINE INDENT while n % i == 0 : NEW_LINE INDENT maxPrime = i NEW_LINE n = n / i NEW_LINE DEDENT while n % ( i + 2 ) == 0 : NEW_LINE INDENT maxPrime = i + 2 NEW_LINE n = n / ( i + 2 ) NEW_LINE DEDENT DEDENT if n > 4 : NEW_LINE INDENT maxPrime = n NEW_LINE DEDENT return int ( maxPrime ) NEW_LINE DEDENT n = 15 NEW_LINE print ( maxPrimeFactors ( n ) ) NEW_LINE n = 25698751364526 NEW_LINE print ( maxPrimeFactors ( n ) ) NEW_LINE