在这个问题中,我有一个变量N.用户将输入N的值。因此,我必须找到2到N之间的质数并将它们存储在数组中
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>(10);
int num,i,j,count;
num = sc.nextInt();
for(i=2;i<=num;i++){
count = 0;
for(j=2;j<= num/2;j++) {
if (i % j == 0) {
count++;
}
}
if(count==0){
array.add(i);
}
}
for(int val: array){
System.out.print(val + " ");
}
}
}
因此,如果N = 15。输出应为2 3 5 7 11 13
但是我得到11 13
问题出在哪里?
答案 0 :(得分:0)
您的逻辑混乱,请考虑定义质数的原因。质数是一个只能被自身和一个整数整除的数字。因此,当您检查余数等于零然后增加计数的质数时,就不会作为count != 0
添加到数组中。我的确意识到您将num / 2的限制设置为j,但不确定您的思考过程是什么。我添加了一个替代解决方案(我尝试坚持使用您的方法,只是对其稍作改动)。
我的思维过程是,当素数除以它本身时,它应该只产生一次零的余数。
ArrayList<Integer> array = new ArrayList<>();
int limit = 100;
int i, j;
for (i = 1; i <= limit; i++) {
count = 0;
j = 2;
for (j = 2; j <= i; j++) {
if(i%j == 0){
count += 1;
}
if (j == i && count == 1) {
array.add(i);
}
}
}
答案 1 :(得分:0)
如果要优化素数搜索,则应使用sieve或至少对算法添加一些简单的限制。我包括了一个带有注释的版本。这样做的主要目的是仅除以已经找到的素数。
List<Integer> primes = new ArrayList<>();
primes.add(2); // seed list with first prime
int max = 50;
// only check odd numbers after 2.
for (int candidate = 3; candidate < max; candidate += 2) {
// loop thru existing primes
for (int p : primes) {
// if candidate is divisible by any prime, then discontinue
// testing and move on to next candidate via outer loop
if (candidate % p == 0) {
break;
}
// if the limit has been reached, then a prime has been
// found, so add to list of primes and continue with
// next candidate.
if (p * p > candidate) {
// add new found prime to list
primes.add(candidate);
break;
}
}
}
System.out.println(primes);