C#求素数

求只能被1和自己整除的正整数。

using System;
using System.Collections.Generic;
using System.Text;

namespace DataStructure
{

public class Prime
{
private static List _prime=new ArrayList();
/// <summary>
/// check prime
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
public static bool isPrime(int a)
{
int i;
for (i = 2; i < a; i++)
{
if (Math.IEEERemainder((float)a, (float)i) == 0) //是否能被i整除
return false;
}
return true;
}
/// <summary>
/// get all prime
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static List getPrime(int min, int max)
{
if (min < 1)
throw new Exception("min must greater than 1");
int i;
for (i = min; i <= max; i++)
{
if (isPrime(i))
_prime.add(i);
}
return _prime;
}
/// <summary>
/// print all prime
/// </summary>
public static void printPrime()
{
_prime.print();
}
}
}

测试:


Prime.getPrime(2, 60);
Prime.printPrime();

结果:

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59

你可能感兴趣的:(C++,c,C#)