判断101-200之间有多少个素数,并输出所有素数

  问题分析:题目中的关键词是素数,什么是素数?素数就是只能被1和自身整除的数,例如11就是素数,但12就不是,因为12可以被1,2,3,4,6和12整除,故12就不是素数;但11就只能被1和11整除,所以11就是素数。

  解决办法:判断素数的经典方法如下是用一个数分别去除2到sqrt(这个数),如果能被整除,
则表明此数不是素数,反之则是素数

方法一 根据基本概念编码

  这里提供一个最基础版的解题代码,直接根据概念编码。

    /**
     * 素数就是只能被1和自身整除的数
     */
    public static void baseSolution() {
        int i = 0, count = 0;
        for (i = 101; i <= 200; i++) {
            if (isPrime(i)) {
                count++;
            }
        }
        System.out.println("素数的个数是:" + count);
    }

    /**
     * 判断一个数是否为素数
     *
     * @param x 待判定的数
     * @return true 是素数
     */
    public static Boolean isPrime(int x) {
        int s = 0, n;
        for (n = 1; n <= x; n++) {
            if (x % n == 0) {
                s++;
            }
        }
        // s > 2说明被1和本身外的数整除
        if (s == 2) {
            // 打印素数
            System.out.println(x);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

方法二 根据平方根求余数

  记end的平方根的上整数为sqrtEnd,根据数学原理,我们知道只要在[begin, sqrtEnd]中不存在可以整除end的数,则end也为素数。故根据此原理编写了如下求解源码:


/**
     * 查找 m和n之间的素数
     *
     * @param begin
     * @param end   小于begin时,提示无素数
     */
    private static void sqrtSolution(Integer begin, Integer end) {

        // 更新步长减少遍历次数
        int len = 1;
        if (begin % 2 == 1) {
            len = 2;
        }
        int i = 0, count = 0;
        for (i = begin; i <= end; i += len) {
            if (isPrimeSqrt(i)) {
                count++;
            }
        }
        System.out.println("sqrtSolution 找到的素数个数是:" + count);
    }

    private static boolean isPrimeSqrt(int x) {
        double max = Math.sqrt(x);
        boolean b = false;
        for (int j = 2; j <= max; j++) {
            if (x % j == 0) {
                b = Boolean.FALSE;
                break;
            } else {
                b = Boolean.TRUE;
            }
        }
        if (b) {
            System.out.println(x);
            return b;
        }
        return Boolean.FALSE;
    }

  测试方法就是一个main 函数:

 public static void main(String[] args) {
    baseSolution();
    sqrtSolution(101, 200);
}
posted @ 2022-12-28 19:36  楼兰胡杨  阅读(892)  评论(0编辑  收藏  举报