見習村10 - Playing with digits

10 - Playing with digits

Don’t say so much, just coding…

Instruction

Some numbers have funny properties. For example:

89 –> 8¹ + 9² = 89 * 1

695 –> 6² + 9³ + 5⁴= 1390 = 695 * 2

46288 –> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd… (a, b, c, d… being digits) and a positive integer p

we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n.

In other words:

Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + …) = n * k

If it is the case we will return k, if not return -1.

Note: n and p will always be given as strictly positive integers.

1
2
3
4
dig_pow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
dig_pow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
dig_pow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
dig_pow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Ruby

Init

1
2
3
def dig_pow(n, p)
# your code
end

Sample Testing

1
2
3
Test.assert_equals(dig_pow(89, 1), 1)
Test.assert_equals(dig_pow(92, 1), -1)
Test.assert_equals(dig_pow(46288, 3), 51)

Javascript

Init

1
2
3
function digPow(n, p){
// ...
}

Sample Testing

1
2
3
Test.assertEquals(digPow(89, 1), 1)
Test.assertEquals(digPow(92, 1), -1)
Test.assertEquals(digPow(46288, 3), 51)

Thinking

想法(1): 與 見習村07 - Sum of Digits / Digital Root 中運用的 recursive 類似
想法(2): 要多判斷今天傳進來的值有可能不是從 1 開始,然後再給他平方後加總,再取餘數來判斷回傳值

https://ithelp.ithome.com.tw/upload/images/20200925/20120826vy9gRts9zq.jpg
圖片來源:Unsplash Jason Strull

Hint & Reference

Solution

Ruby

1
2
3
4
5
6
7
8
9
10
11
# Solution 1
def dig_pow(n, p)
number = n.to_s.split('').map(&:to_i)
sum = number.map.with_index(p) { |num, idx| num ** idx }.reduce(:+)
sum % n == 0 ? sum/n : -1
end

def dig_pow(n, p)
sum = n.to_s.chars.map.with_index(p) { |num, idx| num.to_i ** idx }.reduce(:+)
sum % n == 0 ? sum / n : -1
end

Javascript

1
2
3
4
5
6
7
// Solution 1
function digPow(n, p){
var sum = n.toString().split('')
.map((num, idx) => Math.pow(parseInt(num), idx+p))
.reduce((a,b) => a + b) / n;
return sum % 1 == 0 ? sum : -1;
}