簡體   English   中英

Java中的素數數組

[英]Prime Numbers Array in Java

我想返回一個數組,該數組顯示從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),它檢查某個數字是否是素數。

問題是您的計數器在錯誤的范圍內。 所以而不是遞增。 在第一個 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;


}

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;

將下面的線放在兩個 for 循環之外。 那可行。 問題的原因是 - 您在進入 for 循環時正在重置計數器。

int counter = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM