110,537
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CH11Ex03
{
public class Primes
{
private long min;
private long max;
public Primes(): this(2, 100)
{
}
public Primes(long Min, long Max)
{
if (min<2)
{
min = Min;
}
else
{
min = Min;
}
max = Max;
}
public IEnumerator GetIEnumerator()
{
for (long possiblePrimer = min; possiblePrimer <= max; possiblePrimer++ )
{
bool flag = true;
for (long factor = 2; factor < (long)Math.Floor(Math.Sqrt(possiblePrimer)); factor++)
{
if (0 == possiblePrimer%factor)
{
flag = false;
break;
}
}
if (flag)
{
yield return possiblePrimer;
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CH11Ex03
{
class Program
{
static void Main(string[] args)
{
Primes myPrimes = new Primes(2, 100);
foreach (long num in myPrimes)
{
Console.Write("{0}", num);
}
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var arr = new long[] { 1981, 186, 89, 73, 15, 3, 6, 17, 23, 53 };
Primes myPrimes = new Primes();
foreach(var i in arr)
{
if (myPrimes.IsPrim(i))
Console.Write("{0} ", i);
}
Console.WriteLine("___________按任意键结束");
Console.ReadKey();
}
}
public class Primes
{
public Primes()
{
Found.Add(2);
}
private List<long> Found = new List<long>();
public bool IsPrim(long n)
{
var max = Found.Last();
if (n > max)
{
for (long possiblePrimer = max; possiblePrimer <= n; possiblePrimer++)
{
var top = (long)Math.Floor(Math.Sqrt(possiblePrimer));
foreach (var factor in Found)
{
if (factor > top)
{
Found.Add(possiblePrimer);
break;
}
if (0 == possiblePrimer % factor)
break;
}
}
}
return Found.Contains(n);
}
}
}
这里没有特意做什么优化,但是先把算法搞好,它本身比仅仅去抠一两条语句的“优化”更重要。public class Primes
{
private long min;
private long max;
public Primes()
: this(2, 100)
{
}
public Primes(long Min, long Max)
{
min = Min;
max = Max;
}
private List<long> Found = new List<long>();
public IEnumerable<long> All()
{
bool flag;
for (long possiblePrimer = min; possiblePrimer <= max; possiblePrimer++)
{
var top = (long)Math.Floor(Math.Sqrt(possiblePrimer));
flag = true;
foreach (var factor in Found)
{
if (factor > top)
break;
if (0 == possiblePrimer % factor)
{
flag = false;
break;
}
}
if (flag)
{
Found.Add(possiblePrimer);
yield return possiblePrimer;
}
}
}
}