1
public class Q3
{
public static void main(String args[]){
int i, j;
int Max = 1000;
    //It's obvious that the first fifty prime numbers are less than 1000.
int counter = 1;
while (counter <= 50){
    for (i = 2; i < Max; i++){
        for (j = 2; j < i; j++){
            if ( i % j == 0){
            break;
            }
        }
        if (j >= i){
            System.out.printf("%s ", i);
            counter++;
        }
        if(counter % 10 == 0){
        System.out.print("\n");
        }       
    }
}

}
}

これは、最初の 50 個の素数を 1 行に 10 個リストするために私が書いたプログラムです。ただし、while ループのため、正しく動作していません。実行後、このプログラムは 1000 未満のすべての素数をリストします。while ループがまったく機能していないようです。誰でも理由を教えてもらえますか?どうもありがとう。

4

3 に答える 3

1

素数は最初のforループで生成されます。while 本体は 1 回だけ実行されます。

を削除してwhile、代わりに で別の条件を使用できforます。

for (i = 2; counter <= 50; i++){
于 2013-09-25T08:24:17.217 に答える
0

あなたは大きな問題を抱えています。本当のコードは次のとおりです。

int i, j;
int Max = 1000;
//It's obvious that the first fifty prime numbers are less than 1000.
int counter = 0;
for (i = 2; i < Max && counter < 50; i++){
    for (j = 2; j < i; j++){
        if ( i % j == 0){
        break;
        }
    }
    if (j >= i){
        printf("%d ", i);
        counter++;
         if(counter % 10 == 0){
             printf("\n");
         }  
    }    
}

出力は次のとおりです。23 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 151 157 163 167 173 179 181 191 193 199 211 223 227 229

于 2013-09-25T08:32:25.687 に答える