I was solving https://projecteuler.net/problem=206, and wanted a compile time (consteval) solution.
My idea was to check every number, until the answer is found. However, my code does not compile.
Here is my code:
#include <algorithm>
#include <cstdlib>
#include <print>
#include <ranges>
using namespace std;
consteval auto check_if_square_has_special_form(int x) -> bool
{
long long square = 1LL * x * x;
for (const int digit : {0, 9, 8, 7, 6, 5, 4, 3, 2, 1})
{
const bool last_digit_is_correct = (square % 10) == digit;
if (!last_digit_is_correct)
{
return false;
}
square /= 100;
}
return true;
}
auto concealed_square() -> int
{
const auto positive_numbers = views::iota(1); // Goes on to infinity.
const int answer = *ranges::find_if(positive_numbers, check_if_square_has_special_form);
return answer;
}
auto main() -> int
{
println("The answer is {}", concealed_square());
return EXIT_SUCCESS;
}
This fails to compile, and outputs:
error: taking address of an immediate function 'consteval bool check_if_square_has_special_form(int)'.
Why do I get this error, and how to circumvent it? Using a regular for loop also doesn't seem to work.
constevalto get a value at compile time... So even if this worked it would provide you with no benefit, sincepositive_numbersis not generated at compile time..concealed_squareconstevalas well, but I doubt any compiler will do such heavy compile time calculation (MSVC fails - "failure was caused by evaluation exceeding step limit of 1048576 (/constexpr:steps<NUMBER>)").auto main() -> intIts cute how AAA still survives in some code :Dcheck_if_square_has_special_formto return true (and makeconcealed_squarealsoconstevalin order to use it) - it works. See demo.