Thursday, 10 December 2015

Kata Day 16: Playing with digits


Problem Description: 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, p will always be given as strictly positive integers.

Level: 6kyu

Link to Kata: Playing with digits

As shown in the example above 89 is having properties similar to a funny number. If we add squares of its digits we get a number which can be expressed as a product of two integers out of which 1 integer is 89. We have to find whether the given number has properties similar to a funny number or not.

First we find the sum of squares of individual digits of the given number. Then we initialize a variable to a value of 1 and start a while loop to check if the product of variable and given integer is equal to the sum we calculated.

If we are able to equate the product and the sum, we return true otherwise we continue to increment the value of the variable till the value of product obtained exceeds the sum, in which case we return false.

Here is a link to the code: Kata Day 16

Please mention your suggestions or your doubts in the comment below.

Happy coding. :)

No comments:

Post a Comment