LoginSignup
1
1

More than 3 years have passed since last update.

素数判定 Java

Last updated at Posted at 2019-10-04

素数判定のコードです。
もっと効率のいいコードやきれいなコードがございましたら、アドバイスよろしくお願い致します。

import java.io.*;

class ファイル名{
        public static void main(String[]args) throws IOException
        {
            BufferedReader br =
                new BufferedReader(new InputStreamReader(System.in));

            System.out.print("正の整数を入力してください");
            String str = br.readLine();
            int a =Integer.parseInt(str);

            boolean sosu = true;

            if(a == 1)sosu = false;

            for(int b = 2; b*b <= a; b++){
                if(a%b == 0){
                    sosu = false;
                    break;
                }
            }

            if(sosu == true) System.out.println("\n"+a+"は素数です");
            else System.out.println("\n"+a+"は素数ではありません");


        }
}
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1