用于标识Prime编号asp.net的布尔变量

时间:2014-05-13 10:42:48

标签: c# asp.net loops while-loop boolean

我需要使用布尔变量来识别插入文本框中的数字是否为素数并用C#编写

protected void isPrimeButton_Click(object sender, EventArgs e)
{

    int TestNumber = int.Parse(primeNumberTextBox.Text);
    bool isPrime = true;

    for (int i = 0; i < TestNumber; i++)
    {
        while (TestNumber % i == 0)
        {
            bool isPrime = true;
            yesNoPrimeTextBox.Text = "prime";
            break;
        }

        while (TestNumber % i == 0)
        {
            bool isPrime = false;

            yesNoPrimeTextBox.Text = "not prime";
            break;

        }
    }
}

4 个答案:

答案 0 :(得分:1)

提取 IsPrime作为方法,您将拥有以下内容:

public static Boolean IsPrime(int value) {
  if (value <= 1) 
    return false;
  else if (value <= 3) // 2 and 3 are primes
    return true;
  else if (value % 2 == 0) // even numbers (2 excluded) are not primes
    return false;

  // Test odd numbers 3, 5, 7, ... as potential dividers
  // up to square root of the value
  int n = (int) (Math.Sqrt(value) + 1);

  for (int i = 3; i <= n; i += 2)
    if (value % i == 0)
      return false;

  return true;
}

...

protected void isPrimeButton_Click(object sender, EventArgs e) {
  int testNumber;

  if (!int.TryParse(primeNumberTextBox.Text, out testNumber)) {
    // primeNumberTextBox.Text is not a int (incorrect format)
    //TODO: probably you have to put some text into yesNoPrimeTextBox.Text
    return;
  }

  if (IsPrime(testNumber))
    yesNoPrimeTextBox.Text = "prime";
  else
    yesNoPrimeTextBox.Text = "not prime";
}

答案 1 :(得分:1)

使用此方法检查: 还要考虑更改返回类型,也许你希望它返回boolean而不是string

     public static string CheckPrime(int number) 
    {
        bool isPrime = true;
        for (int i = 2; i < number; i++)
        {
            if (number % i == 0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime)
        {

            return number.ToString() + " is a Prime number";
        }
        else
        {
            return number.ToString() + " is not a Prime number";
        }
    }

答案 2 :(得分:0)

这应该这样做。

protected void isPrimeButton_Click(object sender,EventArgs e) {

int TestNumber = int.Parse(primeNumberTextBox.Text);
bool isPrime = false;

for (int i = 2; i < TestNumber-1; i++)
{
    if (TestNumber % i == 0)
    {
        isPrime = true;
        yesNoPrimeTextBox.Text = "prime";
        break;
    }       
}

}

答案 3 :(得分:0)

效率不高,但这应该有效:

protected void isPrimeButton_Click(object sender, EventArgs e)
{

    int TestNumber = int.Parse(primeNumberTextBox.Text);
    bool isPrime = true;

    for (int i = 2; i < TestNumber; i++)
    {
        if (TestNumber % i == 0)
        {
            isPrime = false;
            break;
        }
    }
    if (isPrime)
        yesNoPrimeTextBox.Text = "prime";
    else
        yesNoPrimeTextBox.Text = "not prime";

}