java-质数输出

1 篇文章 0 订阅

输出质数个数

方法一:设置flag

/*
100以内所有质数的输出
质数也叫素数,只能被1和自身整除的自然数。————> 从2开始到这个数-1为止,都不能被这个数整除。
最小的质数为2
 */
public class PrimeNumberTest {
    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        for(int i = 2; i<= 100000; i++){//遍历100以内的自热数

            boolean isFlag = true;

            for(int j = 2; j< i; j++){//i除以j
                if(i%j == 0){//i被j除尽
                    isFlag = false;
                }
            }
            if(isFlag == true){
                System.out.println(i);
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("计算花费时间:" + (end- begin) + "ms");
    }
}

方法二(改进之——Math.sqrt(i)使用flag

众所周知,假如a=b*c 那么被b整除和被c 整除没啥区别,比如96/2=48,所以在96范围内可以少计算一次,以此类推,只需要遍历[2, i \sqrt{i} i ]能否整除即可

public class PrimeTest2 {
    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        int count = 0;
        boolean isFlag = true;

        for(int i = 2; i<= 100000; i++){//遍历100以内的自热数

            for(int j = 2; j<= Math.sqrt(i); j++){//i除以j
                if(i%j == 0){//i被j除尽
                    isFlag = false;
                    break;//只对本身非质数的数有优化作用
                }
            }
            if(isFlag == true){
               // System.out.println(i);
                count++;
            }
            //重置flag
            isFlag = true ;
        }
        long end = System.currentTimeMillis();
        System.out.println("质数个数为:" + count + "个");
        System.out.println("计算花费时间:" + (end- begin) + "ms");
    }
}

方法三(再改进之——使用continue label

public class PrimeNumberTest3 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();//用于计算时间
        int count = 0;
        label:for(int i=2; i<=100000; i++){
            for(int j= 2; j<= Math.sqrt(i); j++){
                if(i%j == 0){
                    continue label ;//注意label 标签的使用
                }
            }
            count++;
        }
        long end = System.currentTimeMillis();
        System.out.println("时间为"+ (end - start));
        System.out.println("质数的个数为"+ count);
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aertuoliya007

喜欢请投食~~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值