[LeetCode] Count Primes - 素数系列问题
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] Count Primes - 素数系列问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目概述:
Description:Count the number of prime numbers less than a non-negative number, n.
解題方法:
題意是給出n中所有素數的個數。
首先你需要知道判斷一個數是不是素數的方法:(最笨方法但有效)
最初想法是通過兩層循環依次判斷n個數里素數個數,但代碼顯然會TLE。當n=499979時就Time Limit Exceeded,超時代碼如下:
int countPrimes(int n) {int count=0;int i,j;int number;if(n<=1) return 0;for(i=2; i<n; i++) {//分別判斷i是不是素數number = i;for(j=2; j<i; j++) {if(number%j==0) {//除盡表示不是素數break;}}count++;}return count; } 后來找到一種方法,只能說是Perfect。它叫做Sieve of Eratosthenes(埃拉托色尼篩法,簡稱埃氏篩法),參考維基百科:Sieve of Eratosthenes
它的思想是通過建立一個bool型數組,從2開始計數,其倍數的數字都賦值為true,顯然不是素數。最后統計false的個數即為素數個數。
我的代碼:
/*** 題意:計算n中的素數個數* <span style="font-family: Arial, Helvetica, sans-serif;">第二種方法 Sieve of Eratosthenes 埃拉托色尼篩法,簡稱埃氏篩法</span>* By: Eastmount 2015-9-21*/ int countPrimes(int n) {int count;int i,j;bool *nums;if(n<=1) return 0;//動態數組nums記錄是否為素數nums = (bool*)malloc(sizeof(bool)*n);for(i=2; i<n; i++) {//i的倍數均非素數if(!nums[i]) { for(j=2; j*i<n; j++) {nums[j*i] = true;}}}//計算素數個數count = 0;for(i=2; i<n; i++) {if(nums[i]==false) {count++;}}free(nums);return count; }類似題目:
Ugly Number
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
題意:就是子數由2、3、5組成的數字即為Ugly數字,6=2*3、8=2*2*2。
? ? ? ? (By:Eastmount 2015-9-21 凌晨3點半? ?? http://blog.csdn.net/eastmount/ )
總結
以上是生活随笔為你收集整理的[LeetCode] Count Primes - 素数系列问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [LeetCode] Isomorphi
- 下一篇: [C/C++基础知识] 面试再谈stru