Hi guys
I started learning c++ few days ago. I am reading c++ without fear. It is a good book for a beginner like me.
however one of the questions is first prime number greater than 1 billion?
Well i am a slow learner I could not understand the logic, how ever this code has been given by the author but it gives the wrong result.
can any one help me, I have searched net & spent 5 hours on it.
So far i have not covered arrays.
// Exercise 04.01.03
// This program find the first prime number greater
// than one billion (1000000000).
//
#include <iostream>
#include <math.h>
usingnamespace std;
// Function must be declared before being used.
int prime(int n);
int main() {
int i;
// Set up an infinite loop; break if user enters 0.
// Otherwise, evaluate n from prime-ness.
for (i = 1000000000; ; i++) {
if (! prime(i)) { // Call prime(i)
cout << i << " is not prime" << endl;
break;
}
}
return 0;
}
// Prime number function. Test divisors from
// 2 to sqrt of n. Return false if a divisor
// found; otherwise, return true.
int prime(int n) {
int i;
double sqrt_n = sqrt(static_cast<double>(n));
for (i = 2; i <= sqrt_n; i++) {
if (n % i == 0) // If i divides n evenly,
returnfalse; // n is not prime.
}
returntrue; // If no divisor found, n is prime.
}
It's working fine for me. The comment is wrong, however. It says "break if user enters 0", when it should be "break if a number is not prime".
Since 10^9 is not prime, it breaks.
The answer author provided is not in the accordance with the question. The question is
'first prime number greater than 1 billion?"
can some one explain it ?
thank you very much it reeally worked however there is a strange thing
i compiled the code in dev c++ compiler it worked fine but in vc++6 it fives me this error--
"fatal error C1010: unexpected end of file while looking for precompiled header directive
Error executing cl.exe."
can some explain whats going wrong?
I am learning it on my own such kind of pitfalls making me frustrated.