JAVA基础100道练习题——打印1~100之间所有的素数

<1>题目介绍

编写程序,判断1~100之间所有的素数并打印输出

<2>思路分析

素数是在大于1的自然数中,只有1和它本身两个因素的数叫做素数。因此我们只需要将用户输入的数i膜上2~(i-1),如果其中某个环节,余数等于0,就表明i不是素数。如果不满足以上的条件则i为素数

<3>代码实现

    public static void main(String[] args) {
        int i = 1;
        int j = 0;
        for(i=2;i<=100;i++){
            for(j=2;j<Math.sqrt(i);j++){
                if(i%j==0){
                    break;
                }
            }
            if(j>=Math.sqrt(i)){
                System.out.print(i+"\t");
            }
        }
    }

<4>结果展示


 

猜你喜欢

转载自blog.csdn.net/yahid/article/details/123419455