Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 60 / 68

Checking Whether a Number Is Prime

In this lesson you will learn how to test whether a number is prime in C#, covering a basic mathematical algorithm built on a loop. This is for anyone searching for "C# prime number check implementation".

To decide whether a number is prime (divisible only by 1 and itself), check whether it divides evenly by anything from 2 up to its square root. If nothing divides it, it is prime.

The sample code loops over the range for (int i = 2; i * i <= n; i++) and declares the number non-prime the moment it finds an i where n % i == 0. Stopping at the square root works because any larger divisor is always paired with a smaller one.

A common stumbling block for beginners is understanding why the square root is enough. Checking every number below n also gives the right answer, but narrowing the range cuts out wasted work and speeds things up.

This is an important mathematical property that also underpins cryptography, and there is a more advanced technique, the Sieve of Eratosthenes, for finding many primes efficiently at once.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)