前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#版 - Leetcode204. Count Primes - 题解

C#版 - Leetcode204. Count Primes - 题解

作者头像
Enjoy233
发布2019-03-05 15:22:25
5980
发布2019-03-05 15:22:25
举报

Leetcode 204. Count Primes

在线提交: https://leetcode.com/problems/count-primes/description/

Count the number of prime numbers less than a non-negative number, n.

Example:

代码语言:javascript
复制
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

  • Difficulty: Easy
  • Total Accepted: 160.4K
  • Total Submissions: 602.6K
  • Contributor: mithmatt

Case 2:

Input
代码语言:javascript
复制
99999999
Expected answer
代码语言:javascript
复制
5761455

Case 3:

Input
代码语言:javascript
复制
100156172
Expected answer
代码语言:javascript
复制
5769933

分析: 可使用筛法(厄拉多塞Eeatosthese - Sieve Method法)来求素数,从2开始维护一个bool数组isDelete来记录该数是否被删掉,依次删掉当前索引 i 的倍数,最后数组中未被删掉的值(其isDelete值为false)都是素数。

当然除了使用bool数组,还可使用BitArray,如:

代码语言:javascript
复制
public readonly int MaxNum = 1000000;
var numbers = new BitArray(MaxNum, true);
这里写图片描述
这里写图片描述

已AC代码:

代码语言:javascript
复制
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);
        }
    }
}

优化后:

代码语言:javascript
复制
    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#中度量程序运行时间的方法如下:

代码语言:javascript
复制
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");
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年06月09日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Leetcode 204. Count Primes
    • Input
      • Expected answer
        • Input
          • Expected answer
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档