bool primeCheck(unsignedlonglong n)
{
if(n % 2 == 0)
returnfalse;
for(unsignedint i = 3; i < (n/2); i = i + 2)
{
if(n % i != 0)
{
returnfalse;
}
}
returntrue;
}
I was bored so I decided to make a prime checker. This seems to work, though it I'm not sure as it gives an answer almost instantly even with close the largest number I can stick in there (unsigned long long, 17 digit number)
EDIT:
Up to 19 digits, max I can stick in there it seems like. With GCC4.7
They could have all been divisible by two? Either that, or they were breaking something. I have a very good example of a Prime checker. It needs to be speed optimized yet, but it's a smart checker, storing primes into a vector and cross checking them against the new number.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
std::vector<longlong> vPrimes;
// Definition of IsPrime
bool IsPrime(longlong number) {
// Loop through all known primes
for (unsignedint i = 0; i < vPrimes.size(); i ++)
// If number is divisible, it's not prime, return
if (number % vPrimes[i] == 0)
// Return false, was not prime
returnfalse;
// Number was prime, add to vector
vPrimes.push_back(number);
// Return true, was prime
returntrue;
}
Well I wasnt using even numbers for my tests. Just read about the Sieve of Eratosthenes. I'd heard of it before, but never had a reason to actually look it up. It looks really slick, I think I'm gonna work on implementing it.
I like how you did that. When I was doing mine above (I spent about 7 minutes on that lol) I was thinking about using a vector like you did there. May be faster traversing it with a pointer or iterator. But then again, the bracket operator probably uses pointers internally anyway. Someone correct me if I'm wrong.
I think I spent more time writing my comments in than I did actually coding the function. My main isn't pretty either, but took a mere minute to write that as well.
But then again, the bracket operator probably uses pointers internally anyway.
Yes.
Strictly speaking, to prove the primality of n you only need to check divisibility by all positive primes <=sqrt(n). Although I can't say for sure that iterating an array is faster than just checking all naturals <=sqrt(n).