js 数字游戏

在某网站看到一道js题,觉得有点意思

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 * 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⁷ = 236




<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<h1 onclick="digPow(46288,3)">Math</h1>

<script>
    function digPow(n, p){
  // ...
  var len = (n.toString()).length;
  var newString = [];
  var intNum = 0;
  for(var i=0;i<len;i++){
    newString[i] = Math.pow(parseInt(nString[i]),p);
    p++;
    intNum += parseInt(newString[i]);
  }
   if(intNum%n ==0 ){
     var multi = parseInt(intNum/n);
     return multi;
   }else{
       return -1;
   }
}
</script>
</body>
</html>

有更好的方法欢迎推荐!

 

转载于:https://www.cnblogs.com/hubgit/p/6893085.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值