0

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!

Erv Walter
  • 13,737
  • 8
  • 44
  • 57
Justin Montego
  • 125
  • 1
  • 2
  • 6
  • At a glance, you're using a bitwise operator ('&'), and you're also anding all the primenumber % actions. Try using the or operator (`||`) in the second part of your test and change the first `&` to `&&`. – Tim Mar 14 '13 at 16:40
  • 5
    If you are checking divisibility by 2, why check it for 4,6,8, etc. And for a number N to prime all you need to do is check if it is not divisible by any prime number from 2 to squareroot(N). – arunlalam Mar 14 '13 at 16:41
  • 1
    As you are trying to learn. I suggest looking into binary operators and also loops. You will need both to solve this problem – Daniel Moses Mar 14 '13 at 16:41
  • & is bitwise, try using && for logical comparison. Same with the |'s. Edit: Looks like Tim beat me. – Kestami Mar 14 '13 at 16:41
  • 1
    this other post can help you http://stackoverflow.com/questions/1510124/program-to-find-prime-numbers – Byron Mar 14 '13 at 16:52
  • @Tim: The `&` is only a bitwise operator when used with two integers, when used with two booleans it's a logical operator. – Guffa Mar 14 '13 at 16:53
  • 1
    It might be useful to note that `&` is not short-circuited for booleans the way that `&&` is. – Kenneth K. Mar 14 '13 at 17:02
  • @Guffa - I didn't know that. Thanks for the clarification. Thanks Kenneth K for the note on short-circuiting. – Tim Mar 14 '13 at 18:12

5 Answers5

3

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

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

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 &&

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    The `&` operator is only a bitwise operator when used with two integers, with two booleans it's a logical operator. – Guffa Mar 14 '13 at 16:56
  • @Guffa the `&` even with `bool` is still done as a bitwise operation. You can check the IL (it uses the `and` opcode). This is important when you are dealing with true values that have a bit pattern other than 1 – JaredPar Mar 14 '13 at 17:01
  • This is C#, the only value that is true is the value `true`. There are no other values used in boolean operations than `false` and `true`, so there are no other bit patterns that are true. – Guffa Mar 14 '13 at 17:06
  • 1
    @Guffa any non-zero value is considered to be true in .Net and it is possible to have boolean values other than the constant `true` (which has the numeric value of 1). http://blogs.msdn.com/b/jaredpar/archive/2012/08/28/not-all-true-are-created-equal.aspx – JaredPar Mar 14 '13 at 17:10
  • @Guffa here is a gist that demonstrates this problem https://gist.github.com/jaredpar/5163187 – JaredPar Mar 14 '13 at 17:14
  • That's not a boolean value, that is something else that you hack into a boolean variable. A proper boolean value is never anything other than `false` or `true`. – Guffa Mar 14 '13 at 17:28
  • @Guffa the CLR spec disagrees with you. A `boolean` value is explicitly defined to be a byte sized value where 0 is false and != is true. – JaredPar Mar 14 '13 at 17:29
  • Are you trying to prove that `&` is not a logical operator when used on two boolean values? Read the documentation. http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx – Guffa Mar 14 '13 at 17:32
  • @Guffa the documentation is simply wrong in this case. my gist sample clearly demonstrates that `&` is not logical for boolean values. – JaredPar Mar 14 '13 at 17:46
  • No, your sample only demonstrates that you can hack values to break built in operators. – Guffa Mar 14 '13 at 18:02
  • @Guffa how are they hacked? They are specifically identified by the spec as legal values. – JaredPar Mar 14 '13 at 18:05
  • What are you trying to do? Confuse people by stating things that are wrong? – Guffa Mar 14 '13 at 18:09
  • @Guffa what specifically have i said that is wrong? Everything I've said is reproducible and backed up by the CLR spec (partition III, section 1.1.2). It's a subtle corner case but one that can popup in the real world. – JaredPar Mar 14 '13 at 18:35
  • Let me quote you: *"Additionally you don't want to use & in this scenario. That is for bit level and operations."* As there are only boolean operands, it's not a bitwise operator. – Guffa Mar 14 '13 at 21:23
  • @Guffa it is a bitwise operator. Look at the generated IL and the samples i provided. This is simply a fact of the implementation. – JaredPar Mar 14 '13 at 21:50
  • Sigh. Again. Read the documentation. http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx – Guffa Mar 14 '13 at 21:55
  • @Guffa the documentation is **wrong**. The code samples I've provided demonstrably show that `&` is a bitwise operation on boolean values. This is simply a fact that is not subject to debate. – JaredPar Mar 14 '13 at 22:12
  • You chould send a request to Microsoft to change the documenation. However, they will naturally not change the documentation, because it's actually not wrong, which you already know. The code samples that you provide only shows that the IL instruction used to implement the `&` operator is a bitwise instruction, it doesn't show anything about the `&` operator. – Guffa Mar 14 '13 at 22:26
  • @Guffa my code sample shows that it's both implemented as bitwise and behaves as if it's bitwise. You keep saying I'm wrong but so far have not provided any code samples detailing where I'm mistaken and that `&` is truly logical for boolean. Code is king. – JaredPar Mar 14 '13 at 22:37
  • No, they don't. I already explained that it only show the behaviour of the instruction used to implement the operator, it doesn't show anything about the operator. By your logic you can show that `==` is the subtraction operator. Do you want to change the documentation on that also? – Guffa Mar 14 '13 at 22:46
0
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;

}
Ivan Marinin
  • 128
  • 3
  • 9
  • May i ask how i would get it to return a response.write for whether it is true or not. Thank you very much for the code, i understood it and its not giving me any errors. – Justin Montego Mar 14 '13 at 17:17
0

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 (i.e., 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 ;
}
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
0

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;
    }
}
riz
  • 69
  • 1
  • 7