This looks much better. It's much easier to follow the code now.
I'm unclear on one aspect. Should this function return a prime number less than n, or less than or equal to n? In other words, should
inpalprime(13)
return 13 or 11? The
p_test
vector only stores values up to n-1 (the indices of a size n vector go from 0 to n-1), so the final return will always be less than n. But, the first switch statement returns a number equal to n if n is prime and less than or equal to 7.
Also, your program will still crash if you call
ispalprime(6)
or any composite number less than 7. You need to handle the composite numbers below 7 in the initial
switch
.
Finally, an easy optimization:
in the final loop here:
1 2 3 4 5 6 7 8 9
|
//finds the highest possible prime under n
for(std::vector<bool>::size_type a=1; a!=p_test.size(); a++)
{
if((p_test[a]))
{
prime=a;
}
}
return prime;
|
Why not start at the end of the
p_test
, search backwards and return the first value where
p_test[a]
is true? This way, you don't have to search through the entire vector.