经典java编程题

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

 

程序的实现:

 

package com.edu.jmu.classical;

public class Prime {

    public static boolean isDivisible(double integer) {

        int end = new Double(Math.sqrt(integer)).intValue();
        for (int i = 2; i <= end; i++) {
            int mod = (int) (integer % i);
            if (mod == 0) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        for (int i = 100; i < 200; i++) {
            boolean divisible = isDivisible(i);
            if (divisible == false) {
                System.out.println(i + "is a prime");
            }
        }
    }
}
 

 

 

 

运行结果如下:

 

101is a prime
103is a prime
107is a prime
109is a prime
113is a prime
127is a prime
131is a prime
137is a prime
139is a prime
149is a prime
151is a prime
157is a prime
163is a prime
167is a prime
173is a prime
179is a prime
181is a prime
191is a prime
193is a prime
197is a prime
199is a prime

 

你可能感兴趣的:(java,编程)