[c#] Check if number is prime number

  • A prime number is odd except 2
  • 1 or 0 is neither prime nor composite

Approach

  1. Add a counter to check how many times the input number is divisible by i (and has 0 (zero) remainder)
  2. If counter is = 2, then input is prime, else not prime
  3. If counter is > 2 "break" to avoid unnecessary processes (if you want to count the factors of your input number remove " || counter > 2 " on the first if statement)
  4. Add this line of code at the 2nd if statement inside the for loop if you want to see how many numbers with remainder 0 (or factors are present) :
Console.WriteLine( $" {inputNumber} / {i} = { inputNumber / i} (remainder: {inputNumber % i})" ); 
  1. Add the line of code in number 4 (at the end of the for loop) to see all the all the numbers divided by your input number (in case you want to see the remainder output and the quotient)
Console.Write( "Enter a Positive Number: " );
int inputNumber = Convert.ToInt32( Console.ReadLine() );
int counter = 0;

    for ( int i = 1; i <= inputNumber; i++ ) {
        if ( inputNumber == 0 || inputNumber == 1 || counter > 2 ) { break; }
        if ( inputNumber % i == 0 ) { counter++; }
    }

    if ( counter == 2 ) {
        Console.WriteLine( $"{inputNumber} is a prime number." );
    } else if ( inputNumber == 1 || inputNumber == 0 ) {
        Console.WriteLine( $"{inputNumber} is neither prime nor composite." );
    } else {
        Console.WriteLine( $"{inputNumber} is not a prime number. (It is a composite number)" );
    }

My reference: https://www.tutorialspoint.com/Chash-Program-to-check-if-a-number-is-prime-or-not