Jul 30, 2009 at 6:40pm UTC
[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]
Jul 30, 2009 at 6:41pm UTC
problem is, every single number I enter is returned as prime, even if it isn't.
Jul 30, 2009 at 6:56pm UTC
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 Jul 30, 2009 at 7:04pm UTC
Jul 30, 2009 at 9:06pm UTC
Thanks, I just like to combine basic things to make them more complex xD
Jul 30, 2009 at 9:11pm UTC
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.
Jul 30, 2009 at 9:43pm UTC
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 Jul 30, 2009 at 9:56pm UTC
Jul 30, 2009 at 10:49pm UTC
Here's one possible solution:
1 2
for ( i = 2; i <= sqrt( f ) && is_prime; i++ )
is_prime = f % i == 0;
Last edited on Jul 30, 2009 at 10:50pm UTC
Jul 30, 2009 at 11:23pm UTC
@Dudester: Don't just give out solutions, it doesn't help as much as letting them do it themselves.
Jul 31, 2009 at 4:49am UTC
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.
Jul 31, 2009 at 4:44pm UTC
Nvm, I figured it out, it was supposed to be: while ([i<= sqrt(static_cast<double>(f))) not f <=.