2015年9月18日金曜日

素数判定プログラム(java)

メソッド「display()」でint型のデータ(整数)が素数であった場合に「○○は素数です」と表示し、int型のデータ(整数)が素数でなかった場合、「○○は素数ではありません」と表示します。


class Test{
    public static void main(String args[]){
    display(44);
    display(5);
    display(46487);
    display(9724717);
    }

   private static void display(int Num){
         if( isPrimeNum( Num ) ) {
            System.out.println( Num + "は素数です。" );
         } else{
            System.out.println( Num +"は素数ではありません。");
         }
      }

   private static boolean isPrimeNum( int x ) {
         if( x == 2 )
         return true;

         if( x < 2 || x % 2 == 0 )
         return false;

         for( int a = 3; a <= Math.sqrt((double)x); a += 2 )
             if( x % a == 0 )
             return false;
     
         return true;
   }
 }