在线提交: https://leetcode.com/problems/count-primes/description/
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Case 2:
99999999
5761455
Case 3:
100156172
5769933
分析: 可使用筛法(厄拉多塞Eeatosthese - Sieve Method法)来求素数,从2开始维护一个bool数组isDelete来记录该数是否被删掉,依次删掉当前索引 i 的倍数,最后数组中未被删掉的值(其isDelete值为false)都是素数。
当然除了使用bool数组,还可使用BitArray,如:
public readonly int MaxNum = 1000000;
var numbers = new BitArray(MaxNum, true);
已AC代码:
using System;
namespace Leetcode204_GetPrime_SieveMethod
{
public class Solution
{
public int CountPrimes(int n)
{
int count = 0;
bool[] isDelete = new bool[n];
for (int i = 2; i * i < n; i++)
{
if (!isDelete[i])
{
for (int j = i; i * j < n; j++) // Use j to record times(倍数).
{
isDelete[i*j] = true;
}
}
}
for (int i = 2; i < n; i++)
{
if (isDelete[i] == false)
count++;
}
return count;
}
}
class Program
{
static void Main(string[] args)
{
// 以下为测试
Solution sol = new Solution();
var result = sol.CountPrimes(100156150);
Console.WriteLine(sol);
}
}
}
优化后:
public class Solution
{
public int CountPrimes(int n)
{
if (n < 2) return 0;
bool[] isDelete = new bool[n];
int max = (int) Math.Sqrt(n);
var count = 0;
for (int i = 2; i < n; i++)
{
if (isDelete[i])
continue;
count++;
if (i > max)
continue;
for (int j = i * i; j < n; j += i)
isDelete[j] = true;
}
return count;
}
}
Rank: You are here! Your runtime beats60.76 %of csharp submissions.
另外C#中度量程序运行时间的方法如下:
using System.Diagnostics;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//Code
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine(elapsedTime, "RunTime");