C#随机数中选取素数问题
已经从1—100中选取20个随机数了 怎么再在20个随机数中选取其中的素数并排序?public int GetRandom()
{
Random r = new Random();
return r.Next(1, 100);
}
private void button1_Click(object sender, EventArgs e)
{
List<int> result = new List<int>(20);
Random random = new Random();
int temp = 0;
while (result.Count < 20)
{
temp = random.Next(1, 100);
if (!result.Contains(temp))
{
result.Add(temp);
listBox1.Items.Add(temp);
result.Sort();
}
}
} --------------------编程问答-------------------- Random rand = new Random(Guid.NewGuid().GetHashCode());
while (result.Count < 20)
{
temp = random.Next(1, 100);
if (!result.Contains(temp) &&IsPrime(temp) )
{
result.Add(temp);
}
}
result.Sort();
private bool IsPrime(int n)
{
if (n < 2) return false;
else if (n == 2 || n == 3) return true;
else
{
if (n % 2 == 0) return false;
else
{
for (int i = 3; i <= (int)Math.Sqrt(n); i = i + 2)
{
if (n % i == 0) return false;
}
}
}
return true;
}
--------------------编程问答-------------------- 把datas换成你的result
List<int> datas = Enumerable.Range(0, 100).ToList();
Func<int, bool> isPrime = delegate(int x)
{
if (x < 2) return true;
for (int i = 2; i <= Math.Sqrt(x); i++)
if (x % i == 0) return false;
return true;
};
List<int> result = datas.Where(isPrime).ToList();
result.Sort();
foreach (var prime in result)
Console.WriteLine(prime);
--------------------编程问答-------------------- List<int> result = Enumerable.Range(0, 100).ToList();
Func<int, bool> isPrime = delegate(int x)
{
if (x < 2) return true;
for (int i = 2; i <= Math.Sqrt(x); i++)
if (x % i == 0) return false;
return true;
};
List<int> result = result.Where(isPrime).ToList();
result.Sort();
foreach (var prime in result)
Console.WriteLine(prime);
补充:.NET技术 , C#