质数

质数(prime number)又称素数,有无限个。质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数的数称为质数。

在一般领域,对正整数n,如果用2到
之间的所有整数去除,均无法整除,则n为质数。
质数大于等于2 不能被它本身和1以外的数整除
1.  
 public static boolean testIsPrime2(int n){
       if (n <= 3) {
            return n > 1;
        }
        
       for(int i=2;i<n;i++){
           if(n%i == 0)
               return false;
       }
       return true;
   }
 
/*优化后*/
 public static boolean testIsPrime3(int n){
       if (n <= 3) {
            return n > 1;
        }
        
       for(int i=2;i<=Math.sqrt(n);i++){
           if(n%i == 0)
               return false;
       }
       return true;
   }
 
    
    
 
 
2.
public class Prime {
    public static void main(String[] args) {
        int a = 17; //判断17是不是质数
        int c = 0;
        for (int b = 2; b < a; b++) {
            if (a % b != 0) {
                c++;
            }
        }
        if (c == a - 2) {
            System.out.println(a + "是质数");
        } else {
            System.out.println(a + "不是质数");
        }
    }
}

 

posted @ 2016-11-22 11:11  He_quotes  阅读(215)  评论(0)    收藏  举报