C++ Online Compiler
Example: Optimized Prime Finder in Range in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Optimized Prime Finder in Range #include <iostream> #include <cmath> // Required for sqrt() function // Function to check if a single number is prime using optimized trial division bool isPrimeOptimized(int n) { if (n <= 1) { // Numbers less than or equal to 1 are not prime return false; } if (n <= 3) { // 2 and 3 are prime return true; } if (n % 2 == 0 || n % 3 == 0) { // Eliminate multiples of 2 and 3 quickly return false; } // Check for divisors from 5 onwards, skipping multiples of 2 and 3 // All primes greater than 3 can be expressed in the form 6k +/- 1 for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; // If no divisors found, it's prime } int main() { // Step 1: Define the range int lowerBound = 10; int upperBound = 30; std::cout << "Prime numbers in range [" << lowerBound << ", " << upperBound << "] (Optimized):" << std::endl; // Step 2: Iterate through each number in the range for (int i = lowerBound; i <= upperBound; ++i) { // Step 3: Check if the current number is prime using the optimized function if (isPrimeOptimized(i)) { std::cout << i << " "; // Print if it's prime } } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS