# [CodeWars] Playing with digits

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.

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

### My Solution

 #include  class DigPow{public:    static int digPow(int n, int p)    {        auto sum=0;        for(char digit : std::to_string(n)){            sum += pow(digit–‘0’,p++);        }        return sum % n == 0 ? sum/n : –1;    }};Colored by Color Scripter cs

First, I separate a numbers using character data type, and calculated them.
And then, decide the number can be divisible. If it can, returns quotient, if not, returns -1. ## 글쓴이: BakJH

Student of Daedeok SW Meister Highschool, in Korea.

카테고리 Algorithm, Programming태그 ,

## “[CodeWars] Playing with digits”의 2개의 생각

1. BakJH 댓글:

Oh, I read this now. Thank you for your feedback . I’ll provide more interesting codewars kata 🙂

좋아요