C++ Online Compiler
Example: Naive Prime Finder in Range in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Naive Prime Finder in Range #include <iostream> // Function to check if a single number is prime using naive trial division bool isPrimeNaive(int n) { if (n <= 1) { // Numbers less than or equal to 1 are not prime return false; } for (int i = 2; i < n; ++i) { // Try dividing by numbers from 2 up to n-1 if (n % i == 0) { // If divisible, it's not prime 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 << "] (Naive):" << 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 naive function if (isPrimeNaive(i)) { std::cout << i << " "; // Print if it's prime } } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS