Friday, May 15, 2009

Project Euler Problem 3

Problem 3

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

The solution is to find a factor and check if its a prime number. Since we need largest prime factor, run the for loop in reverse direction. Also a prime factor of a number cannot be greater than the square root of the number.


public class ProblemThree {
public static void main(String[] args) {
long range = (long) Math.sqrt(600851475143L);

for (long i = range; i > 1; --i) {
if ((0 == (number % i)) && isPrimeNumber(i)) {
System.out.println(i);

break;
}
}
}

public static boolean isPrimeNumber(long number) {
long halfRange = number / 2;

for (long i = 2; i <= halfRange; ++i) {
if (0 == (number % i)) {
return false;
}
}

return true;
}
}

No comments:

Post a Comment