算法题: 求1至n的素数列表

其实这个题无非就是考怎么编写1个核心函数

f(int n) 判断这个函数是否素数。

首先当今数学家还没有1个求素数的准确公式, 否则大部分都加密算法都可以轻松被破解。

当前的做法是,对于n这个数, 我们会用从2 开始的素数,去逐个去尝试去整除n求余数
如果某个素数能整除, 则这个数是合数。

当然我们不需要从2 开始的素数,一直吃尝试到n -1, 只需要尝试到 n \sqrt{n} n 就ok了。

思路我们就可以做操作了。

代码:

public class primeQuestion {
    public static void main(String... args){
       int n = 200;

       List<Integer> primeList = new PrimeUitl().getPrimeList(n);

       System.out.println(MessageFormat.format("The list of prime numbers up to {0} is {1}", n, primeList));
        
    }
}

/**
 * Algorithm problem: To Get the list of prime numbers from 1 to n
 * 
 */
class PrimeUitl{

    public PrimeUitl(){
        this.primeList.add(2);
    }

    private List<Integer> primeList = new ArrayList<>();

    private List<Integer> outputList = new ArrayList<>();

    public List<Integer> getPrimeList(int n){

        if (n < 3){
            throw new RuntimeException("n must large than 2");
        }
        
        this.outputList.clear();
        this.outputList.add(1);
        this.outputList.add(2);

        for (int i=3; i <= n; i++ ){
            if (isPrime(i)) {
                this.outputList.add(i);
            }
        }

        return this.outputList;
    }

    /**
     * Use a common list of prime numbers to try to divide the integer n. 
     * If the integer n is divisible by a prime number in the list, then n is a composite number,
     * otherwise n is a prime number, and we will add n to the common prime number list.
     * 
     * @param n
     * @return ture of false
     */
    private boolean isPrime(int n){
        for (Integer x: this.primeList){
            if (x > (int) Math.sqrt(n)){
                break;
            }
            
            /*
             * If n is divisible by x, then n is not a prime number
             */
            if (0 == n%x){
                return false;
            } 
            
        }
        this.primeList.add(n);

        return true;
    }

}

输出:

The list of prime numbers up to 200 is [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 
179, 181, 191, 193, 197, 199]
``
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

nvd11

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值