TypeScript: Find Prime Numbers in a Range

1. Introduction

Prime numbers are numbers greater than 1 that have no positive divisors other than 1 and themselves. In this guide, we will explore a TypeScript program to find all prime numbers within a given range.

2. Program Overview

Our objective is to design a function called findPrimesInRange which accepts two integers, representing the start and end of a range. This function will then return an array of numbers, signifying the prime numbers within that range.

3. Code Program

// Function to check if a number is prime
function isPrime(num: number): boolean {
    if (num <= 1) return false;
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) return false;
    }
    return true;
}

// Function to find prime numbers in a range
function findPrimesInRange(start: number, end: number): number[] {
    let primes: number[] = [];
    for (let i = start; i <= end; i++) {
        if (isPrime(i)) {
            primes.push(i);
        }
    }
    return primes;
}

// Testing the function
const start = 10;
const end = 50;
console.log(`Prime numbers between ${start} and ${end} are:`, findPrimesInRange(start, end));

Output:

Prime numbers between 10 and 50 are: 11,13,17,19,23,29,31,37,41,43,47

4. Step By Step Explanation

1. Firstly, we define a helper function isPrime which will ascertain if a number is prime. This is achieved by checking if the number has any divisors other than 1 and itself.

2. If the given number is less than or equal to 1, it can't be prime, so the function returns false.

3. We then iterate from 2 to the square root of the number (a performance optimization) to check for divisors. If we find any divisor, the number is not prime.

4. The main function, findPrimesInRange, initialize an empty array called primes where we'll store the prime numbers.

5. The function iterates through each number in the specified range and checks if the number is prime using the isPrime function.

6. If a prime number is found, it's added to the primes array.

7. Once the iteration is done, the array of prime numbers is returned.

8. We test our function by finding prime numbers between 10 and 50, resulting in the series: 11,13,17,19,23,29,31,37,41,43,47.

Comments