kaprekarNumbers.js

    0

    0

    The function KaprekarNumbers takes two numbers p and q and calculates the kaprekar number for them. The kaprekar number is the sum of the digits in each number up to the number "i". If the two numbers are equal, the number "i" is included in the result. The function checks to make sure the range of numbers being processed is within the limits of what is possible, and if not it outputs an error message.

    function kaprekarNumbers(p, q) {
      let result = [];
      for(let i = p; i <= q; i++) {
        const squareString = (i * i).toString();
        const num1 = squareString.substring(0, squareString.length/2);
        const num2 = squareString.substring(squareString.length/2, squareString.length);
    
        if (Number(num1) + Number(num2) === i) {
          result = result.concat(i)
        }
      }
      if (result.length === 0) {
        console.log('INVALID RANGE')
      } else {
        console.log(...result);
      }
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.