Return all prime numbers smaller than M

后端 未结 9 2128
梦谈多话
梦谈多话 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:44

    This is what I developed for Seive of Eratosthenes. There would be better implementations,of course.

    //finds number of prime numbers less than length

    private static int findNumberOfPrimes(int length) {
        int numberOfPrimes = 1;
        if (length == 2) {
            return 1;
        }
    
        int[] arr = new int[length];
        //creating an array of numbers less than 'length'
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }
        //starting with first prime number 2, all the numbers divisible by 2(and upcoming) is replaced with -1
        for (int i = 2; i < arr.length && arr[i] != -1; i++) {
    
            for (int j = i; j < arr.length; j++) {
                if (arr[j] % arr[i] == 0) {
                    arr[j] = -1;
                    numberOfPrimes += 1;
                }
            }
    
        }
        return numberOfPrimes;
    }
    

提交回复
热议问题