• + 0 comments

    C++ O((q−p+1) log(q)) solution:

    void kaprekarNumbers(int p, int q) {
        bool found_some {false};
        
        for (int i=p; i<=q; i++){
            string square = to_string(static_cast<long>(i) * i);
            int length_square = square.length();
            int length_number = to_string(i).length();
            
            int first_half = (length_square > 1) ? stoi(square.substr(0, length_square-length_number)) : 0;
            int second_half = stoi(square.substr(length_square-length_number));
            
            if (first_half + second_half == i) {
                cout << i << " ";
                found_some = true;
            }
        }
        
        if (!found_some) cout << "INVALID RANGE";
    }