Java中的Prime数组

时间:2017-10-22 14:38:44

标签: java arrays

我想返回一个数组,显示从0到我输入的任何数字的特定范围内的所有素数。

对于从05的范围,我希望使用[2,3,5]返回数组。在我的教授告诉我的任务中,我应该用0填充整个数组,然后再替换那些0个素数。

目前我的代码没有返回正确的数组,因为我似乎没有访问数组中的下一个位置,但似乎总是将值赋给数组中的第一个位置。 我当前的结果数组不是[2,3,5],而是[5,0,0,0,0]。 任何帮助将不胜感激。

public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
Arrays.fill(myAry,0);
for(int i=0;i<myAry.length;i++){
      for (int nextprime=1; nextprime < bis; nextprime++){
          int counter = 0;
         // System.out.println(nextprime);
          if (istPrimzahl(nextprime)){
              myAry[counter] = nextprime;
              counter++;
          }

      }
     System.out.print(myAry[i]+" ");
  }

return myAry;


}

PS:我有一个正常运行的方法(istPrimzahl),它会检查某个号码是否为素数。

3 个答案:

答案 0 :(得分:1)

问题是您的计数器范围错误。 所以不要增加。在第一个for循环的每次迭代中,您声明一个新计数器。因此,在将质数分配给数组时,它为0。

public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
// Arrays.fill(myAry,0);    // no need, this is already been done at initialization
for(int i=0;i<myAry.length;i++){
  int counter = 0;

         // adding <= 'nextprime <= bis;' to check also the last number in the range
      for (int nextprime=1; nextprime <= bis; nextprime++){
         // int counter = 0; wrong scope
         // System.out.println(nextprime);
          if (istPrimzahl(nextprime)){
              myAry[counter] = nextprime;
              counter++;
          }

   }
    if(myAry[0] != 0)    // to get rid of displaying Zeros
       System.out.print(myAry[i]+" ");
  }

return myAry;


}

答案 1 :(得分:0)

ArrayList是比数组更好的选择。但是,如果使用数组是学校的另一项要求,那么你所做的就是:

int[] myAry = new int[size];

已将所有元素设置为零。

也没有必要为此使用2个循环。只是:

  • 从1循环到n
  • 如果当前数字为素数,则将其设置为当前索引数组
  • IDX ++
  

我似乎没有访问数组中的下一个位置,但似乎总是将值赋给数组中的第一个位置。

这是因为您在每次迭代中将计数器变量设置回零。你应该在循环之外声明它。

示例:

int idx = 0;  //place this outside the loop
for(int i=1; i<=n; i++)
    if(isPrime(i))
        myAry[idx++] = i;

答案 2 :(得分:0)

将以下两行放在for循环之外。那可行。 问题的原因是 - 您在进入for循环时重置计数器。

int counter = 0;
相关问题