这道问题是找到第10001个质数,我们解决这个问题需要注意的是:
1. 质数的定义是: 一个数n是质素,当且仅当 n 不能被2到 sqrt(n)之内的任意质数整除;
2. C# 有 return, break,goto 等方法可以让我们跳出两层循环;
3. 打印一个 List<T> 的方法是 list.Foreach(Console.WriteLine);
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectEuler01
{
class Program
{
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
watch.Start();
// Write your code here!
List<int> primelist = new List<int> { 2, 3 };
MyClass pig = new MyClass();
for (int i = 3; primelist.Count < 10001; i=i+2)
{
pig.CheckPnum(primelist, i);
}
//primelist.ForEach(Console.WriteLine); // 注意用默认的 override 打印数组的写法
Console.WriteLine(primelist[9999]);
watch.Stop();
double ts = watch.Elapsed.TotalMilliseconds;
Console.WriteLine("Totoal running time is " + ts + " ms ");
Console.ReadLine();
}
}
class MyClass
{
public List<int> CheckPnum (List<int> mylist, int n)
{
//取一部分数组元素的写法
var checklist = from element in mylist
where element < Math.Sqrt(n)
select element; //只需要检查 2 到 sqrt(n) 之内的质数能不能整除n,即可判断是不是合数;
foreach (int element in mylist)
{
if (n%element ==0)
{
return mylist;
}
}
mylist.Add(n);
return mylist;
}
}
}
另外有一种向后筛法,记录如下:
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectEuler07
{
class Program
{
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
watch.Start();
// Write your code here!
int t1 = Environment.TickCount;
int MAX = 1500000;
BitArray t = new BitArray(MAX); // 初始化的数值都是0
int Count = 1;
for (int x = 3; x < MAX; x += 2)
{
if (!t.Get(x)) // 如果 x 是奇数
{
Count++; // 找到的奇数的个数+1,
if (Count == 10001)
{
Console.WriteLine(x);
break;
}
}
// 关键点1 无论 x 是不是奇数,都会进行到这一步:
// 任何一个数,其整数倍都不会是奇数!
for (int y = 3 ; y*x < MAX; y+=2)
{
t.Set(x*y, true);
}
}
Console.WriteLine("Tid: " + (Environment.TickCount - t1));
watch.Stop();
double ts = watch.Elapsed.TotalMilliseconds;
Console.WriteLine("Totoal running time is " + ts + " ms ");
Console.ReadLine();
}
}
class MyClass
{
}
}