2015-01-03 26 views
0

我正在使用普通數組製作一個幸運數字程序,以便列表中的其餘數字不會向前移動。我所遵循的模式是1,3,7,9,13,15,21,25,31,33,37,43,49,51,63,67,69,73,75,79,87,93 ,99,...欲瞭解更多信息:Lucky Numbers幸運數字程序未顯示正確答案

下面是我製作的節目:

public class LuckyNumbers { 

public static void main(String[] args) { 
    int[] lucky = new int[101]; 

    for (int a = 0; a < lucky.length; a++){ 
     lucky[a] = a; 
    } 
    //goes through each element in list 
    for (int b = 2; b < lucky.length; b++){ 
     //checks if number is surviving 
     if (lucky[b] != 0){ 
      /* if it does survive, go through the list deleting elements 
      * (setting them to zero) that fall on the 
      * index of the multiples of the the surviving number*/ 
      int luckyNum = lucky[b]; // so that the number doesn't change 
      for (int c = 1; c < lucky.length;c++){ 
       int d = luckyNum * c; 
       if (d < lucky.length){ 
        lucky[d] = 0; 
        continue; 
       } 
      } 
     } 
    } 

    for (int f = 0; f < lucky.length; f++){ 
     if (lucky[f] != 0){ 
      System.out.println(lucky[f]); 
     } 
    } 
} 
} 

輸出爲1。我認爲這是一個邏輯錯誤。

+0

是完整的輸出只是「1」或多個「1」? – t3s0

+2

您是否嘗試過調試?您可以看到每個號碼何時被刪除。你的邏輯有幾個問題。程序流程和輸出不是令人驚訝的。因此,我擔心,你的問題不適合Stackoverflow。 –

+0

ISC的實際情況......對Apoorva? – khandelwaldeval

回答

0

第17至23行不會消除第N個剩餘數字。您假設幸運數字數組中的剩餘數字是連續的,但它們不是。您必須掃描/追蹤剩餘的第N個號碼以將其刪除。它需要更多的邏輯,或者找到使這個任務更容易管理的另一個數據結構。

+0

我無法正確理解 –

0

問題是在你的這部分代碼:

for (int c = 1; c < lucky.length;c++){ 
    int d = luckyNum * c; 
    if (d < lucky.length){ 
    lucky[d] = 0; 
    continue; 
    } 
} 

當你看看維基頁面,你必須刪除所有的c個倖存的數量。你正在消除每一個倍數。所以對於第3號,你應該消除5, 11, 17 ...而不是3, 6, 9...現在你在做什麼。

0

這裏,把我的代碼,我沒有爲我校實際項目幸運數字: -

import java.io.*; 
class LuckyNumbers 
{ 
    public static void main(String args[])throws IOException 
    { 
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
    System.out.print("Enter the Number of Elements : "); 
    int n=Integer.parseInt(br.readLine()); 

    int a[]=new int[n]; 
    int c=n; 

    for(int i=0;i<n;i++) 
    { 
     a[i]=i+1; 
    } 

    int del=1; 
    System.out.println("\nLucky Number Operation :\n"); 

    while(del<n) 
    { 
     for(int i=del; i<n; i+=del) 
     { 
      for(int j=i; j<n-1; j++) 
      { 
       a[j]=a[j+1]; 
      } 
      n--; 
     } 
     del++; 

     for(int i=0; i<n; i++) 
     { 
      System.out.print(a[i]+" "); 
     } 
     System.out.println(); 
    } //end of while 

    System.out.print("\nHence, the Lucky Numbers Less than "+c+" are : "); 
    for(int i=0; i<n; i++) 
    { 
     System.out.print(a[i]+" "); 
    } 
    } 
} 
+0

這不是我想要的模式 –