1. Introduction
A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. In this blog post, we will create a TypeScript program to check whether a given number is prime or not.
2. Program Overview
The program defines a function isPrime that checks if a number is prime by testing whether it's divisible by any number less than itself. To optimize this, we only need to test divisibility up to the square root of the number.
3. Code Program
// Function to check if a number is prime
function isPrime(num: number): boolean {
if (num <= 1) return false; // Numbers less than or equal to 1 are not prime
if (num <= 3) return true; // 2 and 3 are prime numbers
// Check divisibility by 2 and 3
if (num % 2 === 0 || num % 3 === 0) return false;
let i = 5;
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) return false;
i += 6;
}
return true;
}
// Test the function
const numberToCheck = 29;
if (isPrime(numberToCheck)) {
console.log(`${numberToCheck} is a prime number.`);
} else {
console.log(`${numberToCheck} is not a prime number.`);
}
Output:
29 is a prime number.
4. Step By Step Explanation
1. We define the isPrime function to check the primality of a number.
2. First, we check if the number is less than or equal to 1. If so, the function immediately returns false since numbers less than 2 aren't prime.
3. We then verify if the number is 2 or 3. These are prime numbers, so we return true.
4. Next, we check if the number is divisible by 2 or 3, returning false if it is.
5. We then loop through numbers greater than 3, up to the square root of the input number, and check for divisibility. Here, we increment by 6 (since we've already checked for divisibility by 2 and 3) and check divisibility for both i and i + 2.
6. If the number is not divisible by any of these numbers, we conclude it's prime.
7. Finally, we test the function with the number 29 and display the result.
Comments
Post a Comment
Leave Comment