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

相关文章
相关标签/搜索