zoukankan      html  css  js  c++  java
  • 204. 计数质数

    统计所有小于非负整数 的质数的数量。

    示例:

    输入: 10
    输出: 4
    解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
    /* int countPrimes(int n)
    {
        int count = 0;
           if(n==0 || n==1) return 0;
        for (int j = 2; j <= n; j++)
        {
            if(isprime(j))
            count++;
        }
        return count;
    }
    /*bool isprime(int n)
    {
        if (n<2)
            return false;
        for (int i = 2; i*i <= n; i++)
        {
            if (n%i == 0)
                return false;
        }
        return true;
    }*/
        /*bool isprime(int num){
        if (num <= 3) {
            return 2;
        }
        // 不在6的倍数两侧的一定不是质数
        if (num % 6 != 1 && num % 6 != 5) {
            return false;
        }
        for (int i = 5; i*i<num; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }*/
        int countPrimes(int n) {
        int sum = 0;
        if (n == 0 || n == 1) return 0;
        for (int i = 2; i<n; i++){
            if (isPrime(i)) sum++;
        }
        return sum;
    }
    bool isPrime(int num){
        if (num == 2 || num == 3)
            return true;
        //不在6的倍数两侧的一定不是质数  
        if (num % 6 != 1 && num % 6 != 5)
            return false;
        int tmp = sqrt(num);
        //在6的倍数两侧的也可能不是质数  
        for (int i = 5; i <= tmp; i += 6)
            if (num %i == 0 || num % (i + 2) == 0)
                return false;
        //排除所有,剩余的是质数  
        return true;
    }

    /*我们继续分析,其实质数还有一个特点,就是它总是等于 6x-1 或者 6x+1,其中 x 是大于等于1的自然数。

    
    

        如何论证这个结论呢,其实不难。首先 6x 肯定不是质数,因为它能被 6 整除;其次 6x+2 肯定也不是质数,因为它还能被2整除;依次类推,6x+3 肯定能被 3 整除;6x+4 肯定能被 2 整除。那么,就只有 6x+1 和 6x+5 (即等同于6x-1) 可能是质数了。所以循环的步长可以设为 6,然后每次只判断 6 两侧的数即可。*/

  • 相关阅读:
    LeetCode 461. Hamming Distance
    LeetCode 442. Find All Duplicates in an Array
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode Find the Difference
    LeetCode 415. Add Strings
    LeetCode 445. Add Two Numbers II
    LeetCode 438. Find All Anagrams in a String
    LeetCode 463. Island Perimeter
    LeetCode 362. Design Hit Counter
    LeetCode 359. Logger Rate Limiter
  • 原文地址:https://www.cnblogs.com/binanry/p/9872331.html
Copyright © 2011-2022 走看看