Your program should prompt the user to type in an integer value n. And you are t
ID: 3651490 • Letter: Y
Question
Your program should prompt the user to type in an integer value n. And you are to compute how many prime numbers are less than or equal to n.Here's what I have thus far:
#include<iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
int count = 0;
cout << "Give me an integer n: " << endl;
cin >> n;
for(i=2; i<=n; i++)
{
count = 1;
for(x=2; x<i; x++)
{
if((i%x) == 0)
{
count = 0;
}
else
{
++count;
}
}
}
cout << "There are " << count << " primes(s) less than or equal to "<< n <<endl;
return 0;
}
Explanation / Answer
#include<iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
int count = 0;
cout << "Give me an integer n: " << endl;
cin >> n;
for(i=3; i<=n; i++)
{
count = 1;
temp = 0;
for(x=2; x<i; x++)
{
if((i%x) == 0)
{
temp++ ;
}
}
if (temp == 0) {
count++ ;
}
}
cout << "There are " << count << " primes(s) less than or equal to "<< n <<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.