• + 0 comments

    Here is my c++ solution, you can what the explanation here : https://youtu.be/MttrQCHGu3w

    int getSum(long a){
        long sq = a * a;
        int digit = (int)log10(a) + 1;
        int result = sq % (int)pow(10, digit);
        int rest = (int)log10(sq) + 1 - digit;
        if(rest > 0) result += stoi(to_string(sq).substr(0, rest));
        return result;
    }
    
    void kaprekarNumbers(int p, int q) {
        bool valid_range = false;
        for(int i = p; i <= q; i++){
            int s = getSum(i);
            if(s == i){
               cout << i << " ";
               valid_range = true; 
            }  
        }
        if(!valid_range) cout << "INVALID RANGE";
    }