Prime number function

[code]
#include <iostream>
#include <math.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
using namespace std;

void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}


int main() {
int f;
int n;
int i;
bool is_prime;



is_prime = true;



cout << "Type a number and press ENTER: " << endl;
cin >> f;
for (n=1; n>0; n--)
{
cout << "Calculation in progress..." << endl;
wait (1);
}
cout << "Calculation complete." << endl;


i = 2;
while (f <= sqrt(static_cast<double>(f))) {

if (f % i == 0)
is_prime = false;
i++;
}



if (is_prime)
cout << "" << f << " is prime.";
else
cout << "" << f << " is not prime.";
getch();
return 0;
}
[code]
problem is, every single number I enter is returned as prime, even if it isn't.
while (f <= sqrt(static_cast<double>(f)))

This will never be true, therefore the loop will not execute and is_prime remains as it was initialized - true.

That fake calculation waiting thing is a little strange (though it gave me a smile). It seems odd that you need to artificially inflate the runtime.
Last edited on
Thanks, I just like to combine basic things to make them more complex xD
I'm confused though, how would I change the while statement? I obviously can't changle the value of is prime, that doesn't fix it.
Well you need to test with every number between 2 and the square root of f. So this seems like more of a situation requiring a for-loop.
Edit: Actually I made a foolish mistake, you should test every number between 2 and the sqaure root of f so long as it hasn't already been proven to not be prime. So I guess you could use either a while or for-loop, but just remember you have those 2 conditions to test for.
Last edited on
Here's one possible solution:
1
2
for( i = 2; i <= sqrt( f ) && is_prime; i++ )
     is_prime = f % i == 0;
Last edited on
@Dudester: Don't just give out solutions, it doesn't help as much as letting them do it themselves.
Try using the sieve of Eratosthenes to find primes. Though this is used to find all the primes between 4 and x not just the primeness of a specific number.
Nvm, I figured it out, it was supposed to be: while ([i<= sqrt(static_cast<double>(f))) not f <=.
Topic archived. No new replies allowed.