Introduction
Prime numbers are numbers greater than 1 that have no divisors other than 1 and themselves. Generating prime numbers is a fundamental concept in computer science and mathematics. This program demonstrates how to generate a list of prime numbers up to a given limit using C++ programming language.
Objective
The objective of this program is to generate a list of prime numbers up to a specified limit input by the user. The program will utilize a straightforward algorithm that checks each number for primality and outputs all prime numbers in the given range.
Prime Number Generator Code in C++
#include #include using namespace std; // Function to check whether a number is prime bool isPrime(int num) { if (num <= 1) return false; for (int i = 2; i <= sqrt(num); ++i) { if (num % i == 0) return false; } return true; } // Function to generate and print prime numbers up to the given limit void generatePrimes(int limit) { cout << "Prime numbers up to " << limit << " are:\n"; for (int i = 2; i <= limit; ++i) { if (isPrime(i)) { cout << i << " "; } } cout << endl; } int main() { int limit; // Ask user for the limit cout << "Enter the limit up to which you want to generate prime numbers: "; cin >> limit; // Generate primes up to the specified limit generatePrimes(limit); return 0; }
Explanation of the Program Structure
This C++ program consists of the following key components:
- isPrime Function: This function takes an integer as input and checks whether it is a prime number. It does so by attempting to divide the number by all integers from 2 up to the square root of the number. If any division results in a remainder of zero, the number is not prime.
- generatePrimes Function: This function iterates through numbers from 2 to the user-specified limit and calls the isPrime function for each number. If the number is prime, it is printed.
- main Function: The main function asks the user to enter a limit for prime number generation, then calls the generatePrimes function to display the primes up to that limit.
How to Run the Program
Follow these steps to run the program:
- Copy the provided code into a new C++ file (e.g.,
prime_generator.cpp
). - Open a terminal or command prompt and navigate to the folder where your file is located.
- Compile the program using a C++ compiler. For example, if you’re using
g++
, run the command:g++ prime_generator.cpp -o prime_generator
- Run the compiled program:
./prime_generator
- The program will ask you to enter a limit, and it will then display all prime numbers up to that limit.