Return all prime numbers smaller than M

后端 未结 9 2131
梦谈多话
梦谈多话 2021-01-02 14:46

Given an integer M. return all prime numbers smaller than M.

Give a algorithm as good as you can. Need to consider time and space complexity.

9条回答
  •  日久生厌
    2021-01-02 15:51

    You can do it using a bottom up dynamic programming approach called the Sieve of Eratosthenes Basically you create a boolean cache of all numbers upto n and you mark each the multiples of each number as not_prime. Further optimizations can be gained by checking only upto sqrt(n) since any composite number will have at least one divisor less that sqrt(n)

        public int countPrimes(int n) {
        if(n==0){
            return 0;
        }else{
            boolean[] isPrime=new boolean[n];
            for(int i=2;i

提交回复
热议问题