[英]JAVA: Method that takes an int “n” as input, and returns an array that contains the first n prime numbers
Here is what I got so far 这是我到目前为止所得到的
public static int[] firstPrimeNumbers(int n) {
int[] k = new int[n];
int m = 0;
for (int i = 0; i < n; i++) {
if (isPrime(i)) {
k[m] = i;
m++;
}
}
return k;
}
Problem is, when I try to print the resulting array, I get a bunch of 0's at the end. 问题是,当我尝试打印结果数组时,最后得到一堆0。 For example when I took
n = 10
, the program printed 例如,当我取
n = 10
,程序打印
2, 3, 5, 7, 0, 0, 0, 0, 0, 0
Hows that even possible? 怎么可能呢? What am I doing wrong?
我究竟做错了什么?
What happens here is fairly easy. 这里发生的事情很容易。
k
has size 10
and initially filled with zeros. k
大小为10
,最初填充为零。
Then you check the first 10 natural numbers and check whether they are prime. 然后,您检查前10个自然数并检查它们是否为质数。 So for each non-prime number you should get a
0
因此,对于每个非素数,您应该获得
0
Maybe replace i<n
by m<n
but that depends a bit on what you want to achieve. 也许将
i<n
替换为m<n
但这在某种程度上取决于您要实现的目标。
You are just counting until i == n
(so only looking at number up to n
) - you need to keep incrementing i
until m == n
so you are considering whether numbers > n
are prime. 你只是计数,直到
i == n
(所以只能看着数量最多n
) -你需要不断递增i
,直到m == n
所以你正在考虑数>是否n
是素数。
If you used better variable names like nextPrimeIndex
or primesFound
instead of m
this would probably be easier to spot. 如果使用更好的变量名(例如
nextPrimeIndex
或primesFound
代替m
,则可能更容易发现。
You should modify your for loop. 您应该修改for循环。 What you are doing is actually returning in an array of
n
elements the primitive numbers less than n
你在做什么其实是在返回的数组
n
元素小于原始数字n
public static int[] firstPrimeNumbers(int n) {
int[] k = new int[n];
int nr = 2;
int m = 0;
while(m<n){
if(isPrime(nr)){
k[m] = nr;
m++;
}
nr++;
}
return k;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.