View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Given a number N, the task is to print the prime numbers from 1 to N.
Examples:
Input: N = 10 Output: 2, 3, 5, 7 Input: N = 5 Output: 2, 3, 5
Algorithm:
- First, take the number N as input.
- Then use a for loop to iterate the numbers from 1 to N
- Then check for each number to be a prime number. If it is a prime number, print it.
Approach 1: Now, according to formal definition, a number ‘n’ is prime if it is not divisible by any number other than 1 and n. In other words a number is prime if it is not divisible by any number from 2 to n-1.
Below is the implementation of the above approach:
C++
#include
using
namespace
std;
bool
isPrime[
int
n]
{
if
[n == 1 || n == 0]
return
false
;
for
[
int
i = 2; i < n; i++] {
if
[n % i == 0]
return
false
;
}
return
true
;
}
int
main[]
{
int
N = 100;
for
[
int
i = 1; i