C Online Compiler
Example: Optimized Prime Number Finder in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Optimized Prime Number Finder #include <stdio.h> #include <stdbool.h> // For boolean type #include <math.h> // For sqrt() function int main() { int lower_bound, upper_bound; // Step 1: Get user input for the range printf("Enter the lower bound of the range: "); scanf("%d", &lower_bound); printf("Enter the upper bound of the range: "); scanf("%d", &upper_bound); printf("Prime numbers between %d and %d are: ", lower_bound, upper_bound); // Step 2: Iterate through each number in the range for (int num = lower_bound; num <= upper_bound; num++) { // Step 3: Handle special cases: numbers less than 2 are not prime if (num <= 1) { continue; } // Handle 2 separately, as it's the only even prime if (num == 2) { printf("%d ", num); continue; } // Skip even numbers greater than 2 immediately if (num % 2 == 0) { continue; } // Step 4: Check for divisibility from 3 up to sqrt(num), only odd divisors bool is_prime = true; // Optimization: check divisors only up to sqrt(num) int limit = (int)sqrt(num); for (int i = 3; i <= limit; i += 2) { // Check only odd divisors if (num % i == 0) { is_prime = false; break; } } // Step 5: If no divisors were found, print the number if (is_prime) { printf("%d ", num); } } printf("\n"); return 0; }
Output
Clear
ADVERTISEMENTS