Print n first primes
Mar 5, 2014 at 10:55am UTC
Hey there guys
Could you please tell me whats wrong with this code? Ive been looking for the error for like 1 hour and still I cant figure out whats missing.
It just prints the number 2 and it doesnt make any sense
Thanks in advance
Cheers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <iostream>
#include <cmath>
using namespace std;
int isprime(int n)
{
int i,fact=0;
for (i=1;i<=n;i++)
{
if (n%i==0);
fact++;
}
if (fact==2)
return 1;
else
return 0;
}
void main()
{
int i = 1;
int count=0;
while (count<100)
{
if (isprime(i)==1)
{
cout<< i << endl;
count++;
}
i++;
}
//system("pause");
}
Mar 5, 2014 at 12:04pm UTC
Notice ; after if. Here what is means:
1 2 3
if (n%i==0)
; //if n is divisible by i then do nothing
fact++; //Always increase fact
Both MSVC and GCC wil warn you about it. Do you have warnings on? If not, turn them on. Either -Wall - Wextra on GCC or /W3 on VS
Also:
void main()
is invalid C++. main should return int
Last edited on Mar 5, 2014 at 12:05pm UTC
Topic archived. No new replies allowed.