LeetCode:Count Primes - 統計質數數量

一、題目名稱java

Count Primes(統計質數數量)數組

二、題目地址less

https://leetcode.com/problems/count-primes/code

三、題目內容ip

英文:Count the number of prime numbers less than a non-negative number, n.leetcode

中文:統計正整數n之內(不含n自己)質數的數量開發

四、一個TLE的方法get

從1到n,考察每一個數字是否爲質數。這個方法因爲花費時間較長,不能知足題目中對時間的要求。io

一段實現此方法的Java代碼以下:class

/**
 * 功能說明:LeetCode 204 - Count Primes
 * 開發人員:Tsybius2014
 * 開發時間:2015年9月6日
 */
public class Solution {
    
    /**
     * 計算n如下的質數數量
     * @param n 正整數
     * @return n如下的質數數量
     */
    public int countPrimes(int n) {
        
        if (n <= 1) {
            return 0;
        }
        
        int result = 0;
        boolean isPrime = true;
        for (int i = 2; i < n; i++) {

            //判斷數字i是否爲質數
            isPrime = true;
            if (i == 2 || i == 3 || i == 5 || i == 7) {
                isPrime = true;
            } else if (i % 2 == 0 || i % 3 == 0 || i % 5 == 0 || i % 7 == 0) {
                isPrime = false;
            } else {
                for (int j = 2; j <= Math.sqrt(i); j++) {
                    if (i % j == 0) {
                        isPrime = false;
                        break;
                    }
                }
            }
            
            //若是i是質數result自增1
            if (isPrime) {
                result++;
            }
        }
        
        return result;
    }
}

四、解題方法

另外一個求質數的方法是埃拉託斯特尼篩法(Sieve of Eratosthenes),這個方法須要聲明一個很是大的數組,但速度較上面的方法要快不少。

一段實現此方法的Java代碼以下:

/**
 * 功能說明:LeetCode 204 - Count Primes
 * 開發人員:Tsybius2014
 * 開發時間:2015年9月6日
 */
public class Solution {
    
    /**
     * 計算n如下的質數數量
     * @param n 正整數
     * @return n如下的質數數量
     */
    public int countPrimes(int n) {
        
        if (n <= 1) {
            return 0;
        }

        int result = 0;
        boolean[] arr = new boolean[n];
        for (int i = 2; i < n; i++) {
            
            //若是arr[i]是質數則將其倍數所有標記爲合數,不然不予考慮
            if (!arr[i]) {
                result++;
            } else {
                continue;
            }

            int j = 2;
            while (i * j < n) {
                arr[i * j] = true;
                j++;
            }
        }
        
        return result;
    }
}

END

相關文章
相關標籤/搜索