I have a function max_palprime(n) that is supposed to find the highest palindromic prime less or equal to n. This function also works together with other two: prime_sieve(m) that generates a sieves of prime numbers up to m, and pal_test(n) that tests if a given number is a palindrome. To simplify the code I already had I was suggested to use the following function for max_palprime(n):
1 2 3 4 5 6 7 8 9 10
longlong inpal::max_palprime(longlong n)
{
auto primes = prime_sieve(n);
auto it = std::find_if(primes.rbegin(), primes.rend(), [&](auto it) {
auto num = primes.size() - std::distance(primes.rbegin(), it)
return *it && pal_test(num);
});
return primes.size() - std::distance(primes.rbegin(), it);
}
but it currently doesnt work because the compiler is telling me that I cant use auto as a lambda parameter. What type do I use in this situation or is there a better way to implement the code?
Here are the other two functions if needed:
prime_sieve(m):
std::vector<bool> inpal::prime_sieve(longlong m)
{
std::vector<bool> p_test(m+1, false);
//defines square root of m
unsignedlonglong root = ceil(sqrt(m));
//sieve axioms
for(unsignedlonglong x=1; x<=root; x++)
{
for(longlong y=1; y<=root; y++)
{
longlong i=(4*x*x)+(y*y);
if (i<=m && (i%12==1 || i%12==5))
{
p_test[i].flip();
}
i=(3*x*x)+(y*y);
if(i<=m && i%12==7)
{
p_test[i].flip();
}
i=(3*x*x)-(y*y);
if(x>y && i<=m && i%12==11)
{
p_test[i].flip();
}
}
}
//marks 2,3,5 and 7 as prime numbers
p_test[2]=p_test[3]=p_test[5]=p_test[7]=true;
//marks all multiples of primes as non primes
for(longlong r=5; r<=root; r++)
{
if((p_test[r]))
{
for(longlong j=r*r; j<=m; j+=r*r)
{
p_test[j]=false;
}
}
}
return p_test;
}
pal_test(n):
1 2 3 4 5 6 7 8 9 10 11 12 13
bool inpal::pal_test(longlong n)
{
//converts n to a string
std::string rev = std::to_string(n);
//checks if the reverse of rev is equal to rev
if(std::equal(rev.begin(), rev.begin()+rev.size()/2, rev.rbegin()))
{
returntrue;
}
returnfalse;
}
Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic.
When indexing C++ containers, such as std::string, std::vector, etc, the appropriate type is the member typedef size_type provided by such containers. It is usually defined as a synonym for std::size_t. http://en.cppreference.com/w/cpp/types/size_t