DEV Community

Cover image for Master Mind-Bending Challenges with Step-by-Step Insights! [Codewars]
Bogdan Galin
Bogdan Galin

Posted on

Master Mind-Bending Challenges with Step-by-Step Insights! [Codewars]

Playing with digits

Image description
Solve:

Image description

Explain:

Image description
This line converts the input number n into a string using String(n) and then converts it into an array of its digits using Array.from
For example, if n is 695, this line would produce an array [6, 9, 5]

Image description
This line initializes a variable total to store the sum of powered digits.
It uses the reduce method to iterate through the digits array (the digits of n) and calculates the sum of each digit raised to the power of p incremented by its position in the number.
acc accumulates the sum, digit represents each digit, and index is the position of the digit in the array.
Math.pow(digit, p + index) calculates the digit raised to the power of p + index.
The 0 at the end of reduce initializes the accumulator (acc) to zero.

Image description
This line checks if the total sum is divisible by n.
If total is divisible by n, it means there exists a positive integer k such that k * n equals the sum of powered digits.

Image description
If the condition in the if statement is true (i.e., total is divisible by n), the function returns total / n, which is the value of k.

In summary, this JavaScript function takes an integer n and an integer p, converts n into its digits, calculates the sum of powered digits, checks if this sum is divisible by n, and returns either the value of k (if it exists) or -1 (if it doesn't).

🚀 Feel free to subscribe to my Boosty! There, you'll discover a treasure trove of helpful tutorials and in-depth problem breakdowns. You can subscribe for free and gain access to a wealth of valuable information. And if you'd like, you can also show your support with a small donation and unlock extra content. ✨ Join Boosty here

Top comments (0)