C Online Compiler
Example: Find Primes in Range using Optimized Function in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Primes in Range using Optimized Function #include <stdio.h> #include <stdbool.h> // For using bool data type #include <math.h> // For using sqrt() function // Function to check if a number is prime (optimized) bool isPrime(int num) { 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 } if (num % 2 == 0 || num % 3 == 0) { return false; // Multiples of 2 or 3 are not prime } // Check for divisibility from 5 onwards // Optimized: only check up to sqrt(num) // and only check numbers of the form 6k ± 1 for (int i = 5; i * i <= num; i = i + 6) { if (num % i == 0 || num % (i + 2) == 0) { return false; // If divisible, it's not prime } } return true; // If no divisors found, it's prime } int main() { // Step 1: Declare variables for the range int lowerBound, upperBound; // Step 2: Get input for the range from the user printf("Enter the lower bound of the range: "); scanf("%d", &lowerBound); printf("Enter the upper bound of the range: "); scanf("%d", &upperBound); // Step 3: Ensure valid range (lower <= upper) if (lowerBound > upperBound) { int temp = lowerBound; lowerBound = upperBound; upperBound = temp; } // Step 4: Print a header for the output printf("Prime numbers between %d and %d are:\n", lowerBound, upperBound); // Step 5: Iterate through the range and check each number for primality for (int i = lowerBound; i <= upperBound; i++) { if (isPrime(i)) { printf("%d ", i); } } printf("\n"); // Newline for better formatting return 0; }
Output
Clear
ADVERTISEMENTS