0

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.

16
  • 2
    std::find_if is called at runtime, why do you think it can call a compile time only function? Commented Sep 26, 2024 at 6:59
  • 1
    Isn't the point of consteval to get a value at compile time... So even if this worked it would provide you with no benefit, since positive_numbers is not generated at compile time.. Commented Sep 26, 2024 at 7:00
  • 2
    Theoretically you could make concealed_square consteval as 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>)"). Commented Sep 26, 2024 at 7:06
  • 1
    auto main() -> int Its cute how AAA still survives in some code :D Commented Sep 26, 2024 at 7:19
  • 2
    @PlsHelp if I change check_if_square_has_special_form to return true (and make concealed_square also consteval in order to use it) - it works. See demo. Commented Sep 26, 2024 at 7:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.