# Answer to Question #56486 in C++ for Nithya

Question #56486

Write a program that asks the user to enter a positive number then displays all numbers less or equal to it that are prime each one a separate line.

Expert's answer

#include <iostream>

#include <vector>

using namespace std;

int main() {

int n;

cin>>n;

bool crossed[n+1];

for(int i=0; i<n; i++) {

crossed[i]=true;

}

vector<int> primes;

crossed[0] = crossed[1] = false;

for (int i=2; i<=n; ++i)

if (crossed[i]) {

primes.push_back(i);

if (i * i <= n)

for (int j=i*i; j<=n; j+=i)

crossed[j] = false;

}

for(vector<int>::iterator it=primes.begin(); it!=primes.end(); ++it) {

cout<<*it<<endl;

}

return 0;

#include <vector>

using namespace std;

int main() {

int n;

cin>>n;

bool crossed[n+1];

for(int i=0; i<n; i++) {

crossed[i]=true;

}

vector<int> primes;

crossed[0] = crossed[1] = false;

for (int i=2; i<=n; ++i)

if (crossed[i]) {

primes.push_back(i);

if (i * i <= n)

for (int j=i*i; j<=n; j+=i)

crossed[j] = false;

}

for(vector<int>::iterator it=primes.begin(); it!=primes.end(); ++it) {

cout<<*it<<endl;

}

return 0;

Need a fast expert's response?

Submit orderand get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

## Comments

## Leave a comment