Find largest prime factor of a 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 ; equivalent to n /= 2 ; 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
< ? php function maxPrimeFactors ( $ n ) { $ maxPrime = -1 ; while ( $ n % 2 == 0 ) { $ maxPrime = 2 ; $ n >>= 1 ; } while ( $ n % 3 == 0 ) { $ maxPrime = 3 ; $ n = $ n / 3 ; } for ( $ i = 3 ; $ i <= sqrt ( $ n ) ; $ i += 2 ) { while ( $ n % $ i == 0 ) { $ maxPrime = $ i ; $ n = $ n / $ i ; } while ( $ n % ( $ i + 2 ) == 0 ) { $ maxPrime = $ i + 2 ; $ n = $ n / ( $ i + 2 ) ; } } if ( $ n > 4 ) $ maxPrime = $ n ; return $ maxPrime ; } $ n = 15 ; echo maxPrimeFactors ( $ n ) , " STRNEWLINE " ; $ n = 25698751364526 ; echo maxPrimeFactors ( $ n ) , " STRNEWLINE " ; ? >