Unlocking the Power of C++: Printing Prime Numbers Between Two Intervals

The Challenge: Printing Prime Numbers

Imagine you’re tasked with writing a program that prints all prime numbers between two given integers. This challenge requires a deep understanding of how to create and utilize functions effectively.

The Solution: printPrime() and isPrime() Functions

To tackle this challenge, we’ll create two functions: printPrime() and isPrime(). The printPrime() function takes two integers, n1 and n2, as input and internally calls the isPrime() function to check if each number between n1 and n2 is prime. If isPrime() returns true, the number is written to standard output; otherwise, no action is taken.

void printPrime(int n1, int n2) {
    for (int i = n1; i <= n2; i++) {
        if (isPrime(i)) {
            std::cout << i << std::endl;
        }
    }
}

The isPrime() function checks if a number is prime by iterating from 2 to the square root of the number and checking for divisibility.

bool isPrime(int num) {
    if (num <= 1) {
        return false;
    }
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

Swapping Numbers: A Crucial Step

But what if the user enters the larger number first? To avoid program failure, we need to swap the numbers. This ensures that num1 is always less than or equal to num2, a crucial assumption made within the printPrime() function’s for loop.

void swap(int &n1, int &n2) {
    int temp = n1;
    n1 = n2;
    n2 = temp;
}

Putting it All Together

By combining these elements, we can create a robust program that efficiently prints prime numbers between two intervals.

int main() {
    int num1, num2;
    std::cout << "Enter two integers: ";
    std::cin >> num1 >> num2;

    if (num1 > num2) {
        swap(num1, num2);
    }

    printPrime(num1, num2);

    return 0;
}

With a solid understanding of C++ fundamentals and effective function creation, you’ll be well-equipped to tackle even the most complex programming challenges.

Leave a Reply