Java经典编程题50道之二十七

求100之内的素数。

public class Example27 {
    public static void main(String[] args) {
        prime();
    }

    public static void prime() {
        System.out.print(2 + " ");
        System.out.print(3 + " ");
        int count = 2;
        boolean flag = false;
        for (int i = 2; i <= 100; i++) {

            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    flag = false;
                    break;
                } else {
                    flag = true;
                }
            }
            if (flag) {
                count++;
                System.out.print(i + " ");
                if (count % 10 == 0) {
                    System.out.println();
                }
            }
        }
        System.out.println(" 共有" + count + "个素数。");
    }
}

原文地址:https://www.cnblogs.com/qubo520/p/6950804.html