first prime number greater than 1 billion.

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.
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
40
41
42
43
// Exercise 04.01.03
// This program find the first prime number greater
//  than one billion (1000000000).
// 

#include <iostream>
#include <math.h>
using namespace 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,
            return false;         //  n is not prime.
    }
    return true;   // 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 ?
You've strangely screwed up the code. It should be

1
2
3
4
         if (prime(i)) {
             cout << i << " is prime" << endl;
             break;
         }

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.
In VC++ you need to go into the project preferences and turn off precompiled headers; alternatively you can just use the empty project option.
Topic archived. No new replies allowed.