Question

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();
    }
}
Was it helpful?

Solution

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!");

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top