I'm relatively new to c++, and I've been trying to write a code to count the number of primes before an arbitrary number. Can you please help me with my code? I don't understand why it isn't working (wrong numbers)
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, i, N=0; //N is the counter
bool isPrime;
cout<<"Enter a value for n"<<endl;
cin>>n;
while(n>0)
{
for(i=2; i<=n/2; i++)
{
if(n%i==0)
{
isPrime=false;
}
else
{
isPrime=true;
}
}
if(isPrime==true)
{
N++;
}
n--;
}
cout<<"Below n there are "<<N<<" prime numbers.";
}
You can't determine that a number is prime until your inner test loop has finished (you've tried all factors). So it doesn't make sense to set isPrime to true within that loop. Instead, you set it as true before the loop (assume true) and then set it to false inside the loop if you find a divisor (and break out of the loop at that point since there's no reason to continue).
Also, you only need to test factors up to the square root of the number, not up to half the number (a big difference!).
#include <iostream>
#include <math.h>
usingnamespace std;
int main() {
int n;
cout << "Enter a value for n: ";
cin >> n;
int cnt = 0;
for ( ; n > 1; n--) {
bool isPrime = true;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime)
cnt++;
}
cout << "Up to " << n << " there are " << cnt << " prime numbers.\n";
}
Since 2 is the only even prime, you can make it more efficient by only testing the odd numbers and handling 2 separately. Also, you don't really need the "isPrime" flag.
#include <iostream>
#include <math.h>
usingnamespace std;
int main() {
int num;
cout << "Enter a value for n: ";
cin >> num;
int n = num;
int cnt = n >= 2 ? 1 : 0; // count prime 2 if within range
if (n % 2 == 0) // ensure n is odd
--n;
for ( ; n > 1; n -= 2) {
++cnt; // assume prime
for (int i = 3; i * i <= n; i += 2)
if (n % i == 0) {
--cnt; // wasn't prime
break;
}
}
cout << "Up to " << num << " there are " << cnt << " prime numbers.\n";
}