#include <iostream>
using namespace std;
int checkIfPrime(int num) {
for (int i = 1; i < num; i++) {
int result = num / i;
if (num == result * i) {
return 0;
}
}
}
int main() {
int i = 3;
while(1) {
int c = checkIfPrime(i);
if (c != 0) {
cout << c << "\n";
}
i = i + 2;
}
}
Sorry about posting the wrong code!
When I run this, nothing happens.. Can someone tell me what I am doing wrong?
After the question has completely changed its meaning:
Your
CheckIfPrimeis just wrong. You’re checking divisibility in a very strange way. The general way to check whetherais divisible bybisif(a % b == 0)That said, your error is that your loop starts with 1. Of course every number is divisible by 1, therefore by your logic, no number is prime. Start with
for(int i = 2; .... (Depending on whether you want to consider 1 as prime or not, you might want to test specially fornum == 1initially.)Also, the end condition is very inefficient. It is enough to check before the square root of num, that is
i <= sqrt(num), but since sqrt is a rather slow and imprecise operation, MUCH better is to loop this way:Another note – to generate all prime numbers from 1 to some MAX_VAL, your approach is very inefficient. Use the Sieve of Erastothenes.
Some stylistic note: your function should ideally return
boolrather thanint, and don’t forget to returntrueor1after the loop has finished without returning.Original Answer:
First of all, you need
instead of
Second, you use the file I/O extremely inefficiently. Why do you open and close the file for every number? You should open it once, write all numbers, and then close it.
And thirdly, your algorithm doesn’t seem to have anything to do with prime numbers… 🙂
By the way, since the first issue results in Undefined Behavior, you can’t complain about any behavior of the program, since it’s… well, undefined.