java每日小算法(2)

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

package test;
public class test {
     public static boolean prime(int num) {
         boolean result = true;
         int dive = num;
         int temp = (int) Math.sqrt(num);
         for(; temp>=2; temp--)
         {
             if(dive==0)
            {
                 result = false;
                 break;
            }
             dive = num%temp;
         }
         return result;
     }
                                  
                              
 public static void main(String[] args) {
     long a = System.currentTimeMillis();
     for(int i = 101; i<=200; i++)
         {
         if(prime(i))
             System.out.println("The prime number : "+i);
         }
     System.out.println(System.currentTimeMillis() - a);
 }
}

The prime number : 101
The prime number : 103
The prime number : 106
The prime number : 107
The prime number : 109
The prime number : 113
The prime number : 118
The prime number : 122
The prime number : 127
The prime number : 131
The prime number : 134
The prime number : 137
The prime number : 139
The prime number : 142
The prime number : 146
The prime number : 149
The prime number : 151
The prime number : 157
The prime number : 158
The prime number : 163
The prime number : 166
The prime number : 167
The prime number : 173
The prime number : 178
The prime number : 179
The prime number : 181
The prime number : 191
The prime number : 193
The prime number : 194
The prime number : 197
The prime number : 199
4


你可能感兴趣的:(java,素数,程序,false)