判断素数

题目:判断101-200之间有多少个素数,并输出所有素数。 
程序分析:
判断素数的方法:
用一个数分别去除2到sqrt(这个数),如果能被整除, 则表明此数不是素数,反之是素数。
2,3例外不能用这个方法,2,3是素数)

    public class Test{
        public static boolean isSushu(int num)
        {
            int i=2;
            for(;i<Math.sqrt(num);i++)
            {
                    if(num%i==0)
                    break;
            }
            return i>Math.sqrt(num);
        }
        public static void main(String args[]){
            int count = 0;
            for(int i=101;i<200;i+=2){//如果这个数是2的倍数就肯定不是素数
                if(isSushu(i)){
                count++;
                }
            }
            System.out.println("count is: "+count);
        }
    }
    /*--运行输出----
    C:\>java Test
    count is: 21
    */

另一个程序:

//该程序使用除1位素数得2位方法,运行效率高通用性差。
//求出1-100内的素数
//用2位数处于一位素数得到所有2位的素数
public class Test{
    public static void main (String[] args){
        int[] a = new int[] {2, 3, 5, 7};
        for (int j = 0; j < 4; j++){
            System.out.print (a[j] + " ");
        }
        boolean b = false;
        for (int i = 11; i < 100; i += 2){
            for (int j = 0; j < 4; j++){
                if (i % a[j] == 0){
                    b = false;
                    break;
                }
                else  b = true;
            }
            if (b == true){
                System.out.print (i + " ");
            }
        }
    }
}
    /*
    C:\>java Test
    2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
    */
原文地址:https://www.cnblogs.com/laoquans/p/2963314.html