namespace text9
{
//在label控件中随机输入20个1~1000之间的整数,求出其中所有的素数的和。
public partial class Form1 : Form
{
int[] nums = new int[20];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int sum = 0;
for (int i = 0; i < nums.Length; i++)
{
if (IsSushu(nums[i]) == true)
{
sum += nums[i];
}
}
sumshow.Text = Convert.ToString(sum);
}
/// <summary>
/// 判断是否是素数的方法;
/// </summary>
/// <param name="n">参数,将要判断的数</param>
/// <returns></returns>
private bool IsSushu(int n)
{
bool flag = false;
if (n < 2)
{
flag = false;
}
else if (n == 2)
{
flag = true;
}
else
{
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
flag = false;
break; //不是质数,此时退出循环
}
else
{
flag = true;//从2到n-1都不能被整除,此时是质数,返回true;
}
}
}
return flag;
}
private void Form1_Load(object sender, EventArgs e)
{
Random r = new Random();
for (int i = 0; i < nums.Length; i++)
{
nums[i] = r.Next(1, 1000);
}
label1.Text = string.Join (",",nums );
}
|