java实现查找101到200间的素数

以两种不同的方法使用java实现查找101到200间的素数。
方法一:
循环遍历101到200,对于每一次遍历都执行,除以2到该数平方根的取余。
方法二:
先找到2到最大值的平方根的倍数,即合数,再剔除掉。
循环遍历101到200的平方根14,对于每一次遍历都执行获取当前值得倍数(从101除以当前值开始),并从列表里将其remove掉。

package test;
import java.util.ArrayList;
/**
 * 101-200之间有多少个素数
 */
import java.util.List;
public class test2 {
    //方法一
    public List<Integer> getSushu1(int min,int max) {
        List<Integer> sushus = new ArrayList<>();
        int count = 0;
        for (int i = min; i <= max;i++) {
            int j;
            for (j = 2; j < Math.sqrt(i); j++) {
                count += 1;
                if (i % j == 0) {
                    break;
                }
            }
            if (j > Math.sqrt(i)) {
                sushus.add(i);
            }
        }
        System.out.println(count);
        return sushus;
    }
    //方法二
    public List<Integer> getSushu2(int min,int max) {
        List<Integer> sushus = new ArrayList<>();
        for(int i = min;i <= max;i++) {
            sushus.add(i);
        }
        int count = 0;
        for (int i = 2; i <= Math.sqrt(max);i++) {
            for(int j = min/i;j<=max/i;j++) {
                count += 1;
                if(sushus.contains(i * j)) {
                    sushus.remove(sushus.indexOf(i* j));
                }
            }
        }
        System.out.println(count);
        return sushus;
    }
    public static void main(String[] args) {
        test2 test2 = new test2();
        System.out.println(test2.getSushu1(101,200));
        System.out.println(test2.getSushu2(101,200));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值