EN
Nopass
Nopass

Codewars [#0 FREE] - 6 kyu

Code:
Explain:
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]
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.
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.
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).

Subscription levels

No subscription levels
Go up