判斷一個數是否是素數

 

  1. package com.test1;  
  2.  
  3. import java.util.Scanner;  
  4. import java.math.*;  
  5.  
  6. public class test8 {  
  7.  
  8.     /**  
  9.      * @param args  
  10.      */ 
  11.     public static void main(String[] args) {  
  12.         // TODO Auto-generated method stub  
  13.  
  14.         Test t = new Test();  
  15.         t.play();  
  16.  
  17.     }  
  18.  
  19. }  
  20.  
  21. class Test {  
  22.     public void play() {  
  23.         System.out.println("請輸入數字");  
  24.         Scanner s = new Scanner(System.in);  
  25.         int m = s.nextInt();  
  26.  
  27.         int k = (int) Math.sqrt(m);  
  28.         int i = 2;  
  29.         // System.out.println(number);  
  30.         for (i = 2; i <= k; i++) {  
  31.             if (m % i == 0) {  
  32.                 break;  
  33.             }  
  34.     }  
  35.       
  36.         if (i > k) {  
  37.             System.out.println("是素數");  
  38.         } else 
  39.  
  40.         {  
  41.             System.out.println("不是素數");  
  42.         }  
  43.  
  44.     }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章