-2

I'm trying to find if a number is prime using C#. I have written the code. It should work but for some reason it doesn't seem to.

This is my code (I've tried inputting 7, 13 etc, says they are not prime):

class Program
{
    static void Main(string[] args)
    {
        long u = Console.Read();
        primefinder(u);
        Console.ReadLine();
    }

    private static void primefinder(long a)
    {
        long counter = 0;
        for (long b = 1; b <= a; b++)
        {
            if ((a % b) == 0)
            {
                counter++;
            }
        }

        if (counter == 2)
        {
            Console.WriteLine("Is prime!");
        }

        else
        {
            Console.WriteLine("Is not prime");
        }

        Console.ReadLine();
    }
}
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
user3204017
  • 51
  • 1
  • 7
  • 1
    you should look at what long u = Console.Read(); returns, I suspect you'll want to parse the string into a integer. – kenny Feb 02 '14 at 17:41
  • 1
    @DmitryBychenko - the algorithm is fine. It is one of the most inefficient, but correct. – Igor Feb 02 '14 at 17:46
  • Have you considered any ways to figure out how or why it doesn't work? – Gabe Feb 02 '14 at 17:51
  • 1
    Go easy on the downvotes and close requests. The OP has made a decent attempt at implementing his algorithm. – Douglas Feb 02 '14 at 17:59

2 Answers2

8

Console.Read reads the next character from the standard input stream, and returns its code point. This is not the same as its integer value. For example, the code point of the character '7' is 55. Additionally, Read only considers a single character; thus, when you type 13, it will only return the code point for '1'.

Instead of Read, you should use ReadLine, which will read an entire line of characters from standard input (i.e. until the user presses "Enter") and return them as a string. Then, you can convert this string into a long value by using its Parse method.

long u = long.Parse(Console.ReadLine());

If you want to avoid getting exceptions when the user enters an incorrect input (such as letters instead of digits), you should use TryParse:

string s = Console.ReadLine();
long u;
if (long.TryParse(s, out u))
    primefinder(u);
else
    Console.WriteLine("Your input was not a valid number!");
Douglas
  • 53,759
  • 13
  • 140
  • 188
1

Console.Read() reads a character from the input and it converts it to a long. It does not read a number.

Modify your code as:

    string input = Console.ReadLine();
    long u = long.Parse(input);
Trifon
  • 1,081
  • 9
  • 19