204. 計數質數

來源:互聯網
上載者:User

標籤:有一個   樣本   大於   如何   nbsp   int   return   輸入   不難   

統計所有小於非負整數 的質數的數量。

樣本:

輸入: 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 兩側的數即可。*/

 

204. 計數質數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.