C Prime Numbers Between Two Intervals Program


A program to find prime numbers between two intervals identifies all the prime numbers within a specified range, which is defined by two input values, mm (the starting point) and nn (the ending point).

Logic to Find Prime Numbers Between Two Intervals:

  1. Input the lower bound mm and the upper bound nn from the user.
  2. Check for prime numbers in the range from mm to nn:
    • For each number in this range, check if it is prime using the same logic as the prime number check (checking for factors up to the square root of the number).
  3. If a number is prime, store it or print it.

Program:

Here’s a C program to find prime numbers between two intervals:

#include <stdio.h> #include <math.h> // Include math library for sqrt function // Function to check if a number is prime int isPrime(int num) { if (num <= 1) return 0; // 0 and 1 are not prime numbers for (int i = 2; i <= sqrt(num); i++) { if (num % i == 0) return 0; // Not a prime number } return 1; // It is a prime number } int main() { int m, n; // Input two integers to define the interval printf("Enter the lower bound (m): "); scanf("%d", &m); printf("Enter the upper bound (n): "); scanf("%d", &n); printf("Prime numbers between %d and %d are:\n", m, n); // Check each number in the interval [m, n] for (int i = m; i <= n; i++) { if (isPrime(i)) { // If the number is prime printf("%d ", i); // Print the prime number } } printf("\n"); // New line for better readability return 0; }

Explanation:

  1. Function isPrime(int num):

    • This function checks if the number numnum is prime.
    • It returns 0 (false) if numnum is less than or equal to 1.
    • It checks for divisors from 2 to the square root of numnum. If any divisor is found, it returns 0. If no divisors are found, it returns 1.
  2. Main Function:

    • The program prompts the user to enter the lower bound mm and the upper bound nn.
    • It iterates over each number in the range [m,n][m, n].
    • For each number ii, it calls isPrime(i). If the function returns 1, ii is printed as a prime number.

Sample Output:

Example 1:

Enter the lower bound (m): 10 Enter the upper bound (n): 30 Prime numbers between 10 and 30 are: 11 13 17 19 23 29

Example 2:

Enter the lower bound (m): 1 Enter the upper bound (n): 50 Prime numbers between 1 and 50 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Key Points:

  • Input Handling: The program allows the user to specify any interval, making it flexible for various ranges.
  • Efficiency: By using the square root check in the isPrime function, the program minimizes the number of iterations required to determine primality.
  • Readability: The output is formatted to clearly display all prime numbers found within the specified range.
  • Separation of Concerns: The prime-checking logic is encapsulated in its own function, improving code organization and maintainability.