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.
1
Expert's answer
2016-01-19T08:28:40-0500
#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;

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS