我正在获取13195L
,24L
和23L
的输出。但是我没有得到600851475143L的输出。系统进入无限循环。请帮助我确定我的代码有什么问题。
package problem3;
public class problem3_version1 {
public static void main(String[] args) {
long dividend = 600851475143L;
// long dividend=13195L;
// long dividend=24L;
// long dividend=23L;
int num_of_divisors = 0;
for (long i = dividend - 1; i >= 2; i--) {
System.out.println("i =" + i);
int count = 2;
for (long j = 2; j < i; j++) {
if (i % j == 0)
count++;
if (count == 3)
break;
}
if (count == 2) {
if (dividend % i == 0) {
num_of_divisors++;
System.out.println("Highest factor is " + i);
break;
}
}
}
if (num_of_divisors == 0)
System.out.println("The number is prime");
}
}
答案 0 :(得分:0)
尝试此解决方案:
public class LargestPrimeFactor
{
public static int largestPrimeFactor(long number) {
int i;
for (i = 2; i <= number; i++) {
if (number % i == 0) {
number /= i;
i--;
}
}
return i;
}
public static void main(String[] args) {
System.out.println(LargestPrimeFactor.largestPrimeFactor(600851475143l));
}
}
问题是因为您嵌套了数量很大的循环,而造成循环的原因