Loading...

Simple TypeScript Function Explained: Is It Prime?

10 4________

Let’s write a simple TypeScript function to check if a number is prime.
Here’s the code:

function isPrime(n: number): boolean {
if (n &lt= 1) return false;
for (let i = 2; i &lt= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
We start by checking if the number is 1 or less — not prime.
Then we loop from 2 to the square root of n. If it divides evenly, it's not prime.
If no divisors are found, the number is prime.
This is a clean, efficient way to test primes in TypeScript — and a great intro to algorithmic thinking.

コメント