Write a C++ program to generate all the prime numbers between 1 and n, where n is a value
Question
Write a C++ program to generate all the prime numbers between 1 and n, where n is a value
Solution
Sure, here is a simple C++ program that generates all the prime numbers between 1 and n:
#include<iostream>
using namespace std;
bool isPrime(int num) {
if(num <= 1)
return false;
for(int i = 2; i * i <= num; i++) {
if(num % i == 0)
return false;
}
return true;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Prime numbers between 1 and " << n << " are: ";
for(int i = 2; i <= n; i++) {
if(isPrime(i))
cout << i << " ";
}
return 0;
}
Here's how it works:
-
The
isPrime
function checks if a number is prime. It does this by checking if the number is divisible by any number up to its square root. If it is, then it's not a prime number. -
In the
main
function, we first ask the user to enter a numbern
. -
We then loop from 2 to
n
(since 1 is not a prime number), and for each number, we check if it's a prime number using theisPrime
function. -
If it is, we print it out.
Similar Questions
Write a C++ program to generate all the prime numbers between 1 and n, where n is a value
Please create a pseudocode function that can check if a given number n is prime or not, where n > 1.
Build the generator primes() function so that you fills the n one at a time, and comes back to primes() function until n > 100.
Write a program to count the number of prime factors of a given positive integer and calculate the difference between the number and the lowest prime factor.
write a program to print integer no, from 1 to n where n is the input from the user using do while loop in c language use getch
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.