Given two integers num1 and num2, print all prime numbers between num1 and num2 (inclusive).
A prime number is a number greater than 1 that has exactly two factors: 1 and itself.

Examples
Input: num1 = 2, num2 = 10
Output: 2 3 5 7
Explanation: The prime numbers in the range from 2 to 10 are 2, 3, 5 and 7.Input: num1 = 10, num2 = 20
Output: 11 13 17 19
Explanation: The prime numbers in the range from 10 to 20 are 11, 13, 17 and 19.
Table of Content
Using for Loop - O((num2 - num1 + 1)√num2) Time, O(1) Auxiliary Space
The for loop traverses the interval, while the isPrime() function checks each number for divisibility.
- Start from num1 and traverse up to num2.
- Check each number using isPrime().
- Print the number if it is prime.
#include <stdio.h>
// Check whether the number is prime
int isPrime(int number)
{
if (number < 2)
return 0;
// Check possible divisors up to square root of number
for (int i = 2; i * i <= number; i++) {
if (number % i == 0)
return 0;
}
return 1;
}
int main()
{
int num1 = 2, num2 = 10;
printf("Prime numbers between %d and %d are: ",
num1, num2);
// Traverse the given interval
for (int i = num1; i <= num2; i++) {
if (isPrime(i))
printf("%d ", i);
}
return 0;
}
Output
Prime numbers between 2 and 10 are: 2 3 5 7
Explanation: The isPrime() function returns 0 when a divisor is found and 1 when no divisor exists. The for loop prints only the numbers for which the function returns 1.
Using while Loop - O((num2 - num1 + 1)√num2) Time, O(1) Auxiliary Space
The while loop provides another way to traverse the interval while using the same isPrime() function.
- Check the current number using isPrime().
- Increment the number after each check.
- Continue until num2 is reached.
#include <stdio.h>
// Check whether the number is prime
int isPrime(int number)
{
if (number < 2)
return 0;
// Check possible divisors up to square root of number
for (int i = 2; i * i <= number; i++) {
if (number % i == 0)
return 0;
}
return 1;
}
int main()
{
int num1 = 2, num2 = 10;
printf("Prime numbers between %d and %d are: ",
num1, num2);
// Traverse the interval
while (num1 <= num2) {
if (isPrime(num1))
printf("%d ", num1);
num1++;
}
return 0;
}
Output
Prime numbers between 2 and 10 are: 2 3 5 7
Explanation: The while loop checks each number and increases num1 after every iteration. The isPrime() function determines whether the current number should be printed.