Tuesday, April 14, 2015

HackerRank::Contests::ProjectEuler::Project Euler #3: Largest prime factor

  First of all, if the number N doesn't have any divisors from 2 to sqrt(N) that means that N is a prime number. First of all let us calculate all the prime numbers from 1 to sqrt ( maxN) which is sqrt(10^12)=10^6. We will use the sieve of Eratostenes for a faster calculation. After that we need to do the following, loop over all the prime numbers, and check for the divisibility of the number on that prime number , if it is divisible then we divide it as long as it's still divisible , Also we memorize the last prime which divided the number, because we need to find the largest prime factor. After this, we have 2 numbers , the number itself ( or the number which is left from the the division of the initial number on the primes), and the largest prime number which divided the initial number. Now, if the remaining number is a prime number we take the one which is greater from the last 2 mentioned numbers, otherwise we print out the found prime number and exit.





No comments:

Post a Comment