Playing with digits

kata programming

مساله:

بعضی از اعداد ویژگی جالبی دارند. برای مثال:

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

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

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

با توجه به عدد صحیح مثبت n نوشته شده به صورت abcd … (a ، b ، c ، d … رقم بودن) و یک عدد صحیح مثبت p:

ما می خواهیم یک عدد صحیح مثبت، اگر وجود داشته باشد، پیدا کنیم که مانند مجموع ارقام n که به توان پی در پی p برسد برابر با k * n شود.

به عبارت دیگر:

(a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + …) = n * k

اگر همچین عددی وجود نداشت -۱ را برگرداند.

همیشه n و p به صورت عدد صحیح مثبت هستند.

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

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.

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

راه حل (Solution):

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class DigPow {
  
  public static long digPow(int n, int p) {
    List<String> nList = Arrays.stream(("" + n).split("")).collect(Collectors.toList());
    int numInPow = IntStream.range(0, nList.size()).reduce(0, (x,y) -> x + (int) Math.pow(Integer.parseInt(nList.get(y)), p + y));
    return (numInPow % n) == 0 ? numInPow / n : -1;
  }
  
}

دیدگاهتان را بنویسید