我正在尝试解决Euler项目中的问题3:
13195的素因子为5、7、13和29。
数字600851475143中最大的素因子是什么?
这是我的密码:
import java.util.ArrayList;
public class Test {
public static void main(String[] args){
long max = 600851475143L;
ArrayList<Long> primes = new ArrayList<>();
primes.add((long) 2);
boolean prime = true;
for (long i = 3; i <= max; i += 2){
for (long j = 3; j < Math.sqrt(i); j++){
if (i % j == 0){
prime = false;
break;
}
}
if (prime) primes.add(i);
else prime = true;
}
for (int i = primes.size() - 1; i >= 0; i--){
if (max % primes.get(i) == 0){
System.out.println(primes.get(i));
return;
}
}
}
}代码没有输出任何东西,它只是给了我一个空白的屏幕。请不要为我解决这个问题,只要告诉我是什么错误,是什么阻止了它输出任何东西。
发布于 2020-03-27 16:10:36
当你没有素数的时候,你是在浪费时间计算所有的素数。
当您找到第一个素数时,尝试将divisible.
假设您正确地找到了素数(我相信您是这样的),那么请考虑以下几点:
primes = 2,3,5,7,11,13
max = 99
is 99 divisible by 2 - no, try next prime.
is 99 divisible y 3 - yes
max = 33
is 33 divisble by 3 - yes
max = 11
is 11 divisible by 3 - no
by 5 - no
by 7 - no
by 11 - hey, max is a prime! And it must be the largest because
it can't be reduced anymore.如果你想要的话,当你找到最大的每个素因子时,把它保存在一个列表中。
然后乘以列表中的所有值,以查看产品==最大值是否最大。
这是你的代码
import java.util.ArrayList;
public class Test {
public static void main(String[] args){
long max = 600851475143L;
// right here, reduce max by current prime (which starts at 2)
for (long i = 3; i <= max; i += 2){
boolean prime = true;
for (long j = 3; j < Math.sqrt(i); j++){
if (i % j == 0){
prime = false;
break;
}
}
if (prime) {
// right here, reduce max by current prime
}
}
}
}发布于 2020-03-27 16:11:21
你确定你的程序已经完成了吗?我在下面添加了下面的代码,看起来第一个for循环需要很长时间才能完成,这可能就是为什么您没有看到任何输出。要查看您的进度,请尝试添加如下所示的print语句:
import java.util.ArrayList;
public class Test {
public static void main(String[] args){
long max = 600851475143L;
ArrayList<Long> primes = new ArrayList<Long>();
primes.add((long) 2);
boolean prime = true;
for (long i = 3; i <= max; i += 2){
if(i % 1000005 == 0)
System.out.println("i = " + i);
for (long j = 3; j < Math.sqrt(i); j++){
if (i % j == 0){
prime = false;
break;
}
}
if (prime) primes.add(i);
else prime = true;
}
for (int i = primes.size() - 1; i >= 0; i--){
if (max % primes.get(i) == 0){
System.out.println(primes.get(i));
return;
}
}
}
}https://stackoverflow.com/questions/60889413
复制相似问题