# .Net4 Expression Tree 入门(4): 求N以内的所有质数

#### 求N以内的所有质数

##### 一般的写法
static List<int> GetPrimes_SimpleMethod(int to)
{
var res = new List<int>();
for (int n = 2; n <= to; n++)
{
bool found = false;

for (int d = 2; d <= Math.Sqrt(n); d++)
{
if (n % d == 0)
{
found = true;
break;
}
}

if (!found)
}
return res;
}


for (int n = 2; n <= to; n++)
{
// do sth…
}


int n = 2;
while (true)
{
if (!(n <= to))
break;
// do sth…
n++;
}

##### 求N以内的所有质数的“NoFor” 写法

【纯粹是为了更方便构造 Expression Tree，否则相信没人用while(true)这样写法】

static List<int> GetPrimes_NoFor(int to)
{
var res = new List<int>();
int n = 2;
while (true)
{
if (!(n <= to))
break;
bool found = false;

int d = 2;
while (true)
{
if (!(d <= Math.Sqrt(n)))
break;

if (n % d == 0)
{
found = true;
break;
}

d++;
}

if (!found)

n++;
}
return res;
}


##### 上述代码与表达式的对比列表
 原始代码 表达式 var res = new List(); Expression.Assign( res, Expression.New(typeof(List)) )  int n = 2; Expression.Assign( n, Expression.Constant(2) )  while (true) { if (!(n <= to)) break;  Expression.Loop( Expression.Block( Expression.IfThen( Expression.Not( Expression.LessThanOrEqual( n, to ) ), Expression.Break(breakOuter) )  Math.Sqrt(n) Expression.Call( null, typeof(Math).GetMethod("Sqrt"), Expression.Convert( n, typeof(double) ) )  d++; Expression.PostIncrementAssign(d)  res.Add(n); Expression.Call( res, typeof(List).GetMethod("Add"), n ) 

 原始代码 表达式 var res = new List(); res.Assign(Expression.New(typeof(List)))  int n = 2; n.Assign(2)  n ++; n.PostIncrementAssign()  for (int n = 2; n <= to; n++) Expression.For(n, n.Assign(2), n <= to, n.PostIncrementAssign()  res.Add(n); res.Method("Add", n)

posted on 2010-05-26 14:59  CoolCode  阅读(2756)  评论(0编辑  收藏  举报