入力した値までの素数を表示し、入力した値までに何個素数があるかを出力したいです。
ifの条件式をどうすれば正しい結果がだせるのでしょうか。
発生している問題・エラーメッセージ
エラーは出ないのですが、実行すると結果が間違った表示になってしまいます。
該当のソースコード
java
import java.io.*;
class Test05_3
{
public static void main(String[] args)throws IOException
{
System.out.println("いくつまで?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int num = Integer.parseInt(str);
int count=0;
for(int i = 2; i < num; i++){ for(int j = 2; j < i; j++){ if(i % j != 0){ System.out.println(i + ", "); count++; } else if(i % j == 0)break; } } System.out.println("\n素数は"+ count +"個です"); }
}
試したこと
いくつまで?
50
3,
5,
5,
5,
7,
7,
7,
7,
7,
9,
11,
11,
11,
11,
11,
11,
11,
11,
11,
13,
13,
13,
13,
13,
13,
13,
13,
13,
13,
13,
15,
17,
17,
17,
17,
17,
17,
17,
17,
17,
17,
17,
17,
17,
17,
17,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
21,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
25,
25,
25,
27,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
29,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
31,
33,
35,
35,
35,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
37,
39,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
41,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
43,
45,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
49,
49,
49,
49,
49,
素数は316個です
このような結果が出てしまいます。
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。