简体   繁体   中英

Asp with C# Prime Number

I'm a 17 year old student currently in software engineering and web development and im having trouble right now with some of my coding. I need to make a project that will alow the user to input a number anywherefrom 0 to 999 and tell whether it is a prime number or not. The code i have so far is....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public void primeNumber()

    {

        int primeNumber1 = int.Parse(Request.Form["Text4"]);

        if (primeNumber1 % 1 == 0 &  !           (primeNumber1 % 2 == 0 &
                                                  primeNumber1 % 3 == 0 &
                                                  primeNumber1 % 4 == 0 &
                                                  primeNumber1 % 5 == 0 &
                                                  primeNumber1 % 6 == 0 &
                                                  primeNumber1 % 7 == 0 &
                                                  primeNumber1 % 8 == 0 &
                                                  primeNumber1 % 9 == 0))
                {
            Response.Write(" This is a prime number! ");
        }

        else
        {
            Response.Write(" This is not a prime Number! ");
        }


    }
}

... but i cannot get this program to display the correct answer. Any help would be greatly appreciated. Thanks!

You have got the concept of prime numbers wrong. Your code would for example report that 3 is not a prime number, because you check if the number divides evenly in three even if the number entered is three.

The simplest solution would be to loop from 2 and up to primeNumber1 - 1 and check if any of those divides evenly with the number. As you are using a loop, you also need a variable to hold what the result was, as you don't have a single expression that returns the result.

Something like:

bool prime = true;
for (int i = 2; i <= primeNumber1 - 1; i++) {
  if (primeNumber1 % i == 0) {
    prime = false;
  }
}

This is of course the simplest possible solution that solves the problem, for reasonably small numbers. You can for example improve on the solution by exiting out of the loop as soon as you know that it's not a prime number.

You also don't need to loop all the way to primeNumber1 - 1 , but only as high as the square root of the number, but you can find out about that if you read up on methods for checking prime numbers.

You need to handle the special cases of 1 and 2 also. By definition 1 is not a prime number, but 2 is.

http://en.wikipedia.org/wiki/Prime_number

Anytime you find yourself in programming repeating a test on a sequential range of numbers you're doing the wrong thing. A better construct for this is a loop. This will give you the range of numbers in an identifier which can then be used to write the repetive code one time. For example I could rewrite this code

primeNumber1 % 2 == 0 &
primeNumber1 % 3 == 0 &
primeNumber1 % 4 == 0 &
primeNumber1 % 5 == 0 &
primeNumber1 % 6 == 0 &
primeNumber1 % 7 == 0 &
primeNumber1 % 8 == 0 &
primeNumber1 % 9 == 0))

As follows

bool anyFactors = false;
for (int i = 2; i <= 9; i++) {
  if (primeNumber1 % i != 0) { 
    anyFactors = true;
    break; 
  }
}

At this point I can now substitute the value allTrue for the original condition you wrote.

if (primeNumber1 % 1 == 0 && !anyFactors)

I can also expand the number of values tested here by substiting a different number for the conditional check of the loop. If I wanted to check 999 values I would instead write

for (int i = 2; i <= 999; i++) { 
  ...
}

Additionally you don't want to use & in this scenario. That is for bit level and operations. You are looking for the logical and operator &&

bool IsPrime(int number) {

    if (number == 1) return false;
    if (number == 2) return true;

    for (int i = 2; i < number; ++i)  {
       if (number % i == 0)  return false;
    }

    return true;

}

A little google-fu or a little navel-gazing about prime numbers in general, will lead you to the naive algorithm:

For all n such that 0 < n:

  • There are two "special case" prime numbers, 1 and 2 .
  • All even numbers > 2 are non-prime, by definition
  • If you think about the nature of factoring, the largest possible factor you have to consider is the square root of n , since above that point, the factors are reflexive (ie, the possible factorizations of 100 are 1*100 , 2*50 , 4*25 , 5*20 , 10*10 , 20*5 , 25*4, 50*2 and 100*1 — and the square root of 100 is...10).

That should lead you to an implementation that looks something like this:

static bool IsPrime( int n )
{
  if ( n < 1 ) throw new ArgumentOutOfRangeException("n") ;

  bool isPrime = true ;
  if ( n > 2 )
  {

    isPrime = ( 0 != n & 0x00000001 ) ; // eliminate all even numbers

    if ( isPrime )
    {
      int limit = (int) Math.Sqrt(n) ;
      for ( int i = 3 ; i <= limit && isPrime ; i += 2 )
      {
        isPrime = ( 0 != n % i ) ;
      }
    }
  }
  return isPrime ;
}

Try the code below:

bool isPrimeNubmer(int n)
{
    if (n >=0 && n < 4) //1, 2, 3 are prime numbers
        return true;
    else if (n % 2 == 0) //even numbers are not prime numbers
        return false;
    else
    {
        int j = 3;
        int k = (n + 1) / 2 ;

        while (j <= k)
        {
            if (n % j == 0)
                return false;
            j = j + 2;
        }
        return true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM