Why does isprime((int n) work?

From: Rusty Shackleford (johndoe_at_nospam.com)
Date: 08/05/04

```Date: Thu, 05 Aug 2004 03:45:33 GMT

```

I googled for "c++ prime" and found this isprime() function. I added 'int
main()' to test the function but I do not understand how the 'for loop'
works. If I add a 'count << divisors << endl;' right before the return on
the isprime() function and then input a 10000 it shows that it is composite
and divisors is incremented 25 times but if I input 10007 it only increments
2 times. It seems to me that 'if(n % i==0) in the for loop would have to at
least increment 'divisors' 25 times with the input of 10007 but it does not.
How does it drop back to 2 with 10007 iterations? I have seen many
isprime() algorithms but this one is hard to understand. At least for me
anyway.

#include <iostream>

using namespace std;

bool isprime(int n); // Function Protocall

int main() {

int n;

cout << "input number: ";
cin >> n;

if(isprime(n)==TRUE)
cout << "number is Prime" << endl;
else
cout << "number is Composite" << endl;

cin.sync();
cin.get();
return 0;
}

bool isprime(int n) {

int divisors, i;

divisors = 0;
for(i = 1;i <=n;i++) {
if(n % i==0)
divisors++;
}

return(divisors==2);
}

```--
Rusty Shackleford
'What ever happens, happens necessarily'
mhaefner@NOSPAMsbcglobal.net