求600851475143最大的素数因子

/**
* The prime factors of 13195 are 5, 7, 13 and 29.
*
* What is the largest prime factor of the number 600851475143 ?
*/

代码:

private static long maxPrime(long N) {
int max = 1;
if (N % 2 == 0)
max = 2;
for (int i = 1; i <= Math.sqrt(N); i = i + 2)
if (N % i == 0) {
if (isPrime(N / i))
return N / i;
else if (isPrime(i))
max = i;
}
return max;
}

private static boolean isPrime(long n) {
if (n % 2 == 0)
return false;
for (int i = 3; i <= Math.sqrt(n); i = i + 2)
if (n % i == 0)
return false;
return true;
}

public static void main(String[] args) {
System.out.print(maxPrime(600851475143L));
}

思想:

很不幸的这个数超过int的范围,只好用long来解答。

解题过程中没有取巧,但是在判断素数时可以使步长+2,在迭代N本身最大的素数因子时,也可以使步长+2,因为偶数除了2都不是素数