Check Prime Number in C#

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 2 Code Examples
Number theory

What you’ll learn

  • What makes a number prime (exactly two positive divisors).
  • Why checking divisors only up to sqrt(n) is enough.
  • Two C# programs: one-number test and prime listing in a range.
  • A live preview, edge cases, and optimization notes.

Overview

A prime number is greater than 1 and divisible only by 1 and itself. Instead of checking all numbers up to n - 1, we stop at sqrt(n) to keep checks efficient.

Single check

Determine if one value like 17 is prime.

Range listing

Print all primes from 1 to 20 using the same helper.

Fast bound

Stop divisor checks at i * i <= n.

Prerequisites

Loops, modulo operator %, and integer comparisons.

  • Prime numbers are integers greater than 1.
  • If any divisor exists in [2, sqrt(n)], n is not prime.

Understanding the concept of prime numbers

A prime number has exactly two positive divisors: 1 and itself. Examples: 2, 3, 5, 7, 11, 13.

Values <= 1 are not prime, and 2 is the only even prime. A natural number greater than 1 that is not prime is called composite.

Square-root bound

If n = a × b, then at least one of a or b is <= sqrt(n). So checking divisibility only up to sqrt(n) is sufficient.

Result

No divisor up to sqrt(n) means n is prime.

Quick examples

17Prime
Check
No divisors in 2..4
18Not prime
Check
Divisible by 2
2Prime
Special
Only even prime

Live preview

Runs the same square-root trial-division logic as the C# examples.

Live result
Press “Run check”.

Algorithm

Goal: determine whether integer n is prime.

Reject small values

If n <= 1, return false.

Check divisors

Loop i from 2 while i * i <= n.

Return verdict

If any n % i == 0, not prime; otherwise prime.

📜 Pseudocode

Pseudocode
function isPrime(n):
    if n <= 1:
        return false
    for i from 2 while i * i <= n:
        if n mod i == 0:
            return false
    return true
1

Check one number

Reference program: tests whether 17 is prime using trial division up to sqrt(n).

c#
using System;

class Program
{
    static bool IsPrime(int number)
    {
        if (number <= 1)
            return false;

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

        return true;
    }

    static void Main()
    {
        int testNumber = 17;

        if (IsPrime(testNumber))
            Console.WriteLine($"{testNumber} is a prime number.");
        else
            Console.WriteLine($"{testNumber} is not a prime number.");
    }
}
2

Prime numbers in range 1 to 20

Reuses IsPrime inside a range loop — matches the reference range output.

c#
using System;

class Program
{
    static bool IsPrime(int number)
    {
        if (number <= 1)
            return false;

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

        return true;
    }

    static void Main()
    {
        Console.WriteLine("Prime Numbers in the Range 1 to 20:");

        for (int i = 1; i <= 20; i++)
        {
            if (IsPrime(i))
                Console.Write($"{i} ");
        }

        Console.WriteLine();
    }
}

Optimization and alternatives

Square-root bound. Use i * i <= n (or cast to long) instead of looping to n - 1.

Skip evens. After handling 2, test only odd divisors to reduce constant work.

Math.Sqrt. You can write i <= Math.Sqrt(number), but integer multiplication avoids floating-point rounding issues.

❓ FAQ

A prime number is an integer greater than 1 that has exactly two positive divisors: 1 and itself.
No. By definition, prime numbers start from 2.
If n has a factor bigger than sqrt(n), the paired factor must be smaller than sqrt(n), so checking up to sqrt(n) is enough.
2 has only two divisors: 1 and 2. It is also the only even prime.
In this tutorial, primality is defined for integers greater than 1, so negatives are not prime.
The square-root trial division check runs in O(sqrt(n)) time and O(1) extra space.

🔄 Input / output examples

nResult
17Prime
18Not prime (divisible by 2)
1Not prime
2Prime

Edge cases and pitfalls

n <= 1

Not prime

Values 1, 0, and negatives are not prime in this tutorial.

n = 2

Smallest prime

2 is prime and the only even prime.

Overflow

Large n

Use (long)i * i <= number to avoid overflow in the loop condition.

⏱️ Time and space complexity

MethodTimeExtra space
Single prime check (sqrt bound)O(√n)O(1)
Check all numbers in range 1..Uabout O(U√U)O(1)

Summary

  • Primes are integers > 1 with exactly two divisors.
  • Use trial division up to sqrt(n)O(sqrt(n)) per check.
  • From 1 to 20, primes are 2 3 5 7 11 13 17 19.
Did you know?

2 is the only even prime number. 1 is neither prime nor composite.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful