[英]Javascript: Why are my numbers not being raised to the nth power and being pushed to my array?
I am trying to write a function that takes in a number and sums its range of digits to the nth power, but it seems like my function is not properly "n-thing" each number in the array. 我正在尝试编写一个函数,该函数接受一个数字并将其数字范围求和为n次幂,但似乎我的函数未正确“对数组中的每个数字进行n运算”。
Here's my code: 这是我的代码:
function sumDigPow(a, b) {
var premArray = [];
var squaredArray = [];
for(var i = a; i <= b; i++){
premArray.push(i);
}
for(var j = 0; j < premArray.length; j++){
var squared = ('' + premArray[j]).split('').map(function(v, i){
return Math.pow(parseInt(v), i + 1);
}).reduce(function(a , v){
return a + v;
}, 0);
squaredArray.push(squared);
}
}
sumDigPow(5,22);
This will return the sum of the digits of n taken to the successive powers 这将把取n的数字的总和返回到连续的幂
function sumDigPow(a, b) {
var squared = String(a).split('').map(function(v){
return Math.pow(parseInt(v), b++);
}).reduce(function(a , v){
return a + v;
});
return squared;
}
sumDigPow(89, 1) => 89 sumDigPow(89,1)=> 89
sumDigPow(695, 2) => 1390 sumDigPow(695,2)=> 1390
sumDigPow(46288, 3) => 2360688 sumDigPow(46288,3)=> 2360688
You pretty much over complicated entire thing. 您几乎要处理整个复杂的事情。
function digPow(n, p){
var total = 0;
var digits = (""+n).split("");
for (var i = 0; i< digits.length; i++) {
total += Math.pow(digits[i], p+i);
}
if(total/n % 1 === 0){
return total/n;
}
return -1;
}
Here we split first number to array. 在这里,我们将第一个数字拆分为数组。 Mind that string times number can produce number if string is that of a number example: "6".
请注意,如果字符串是数字示例,则字符串乘以数字可以产生数字:“ 6”。
So we just split it, iterate through and calculate total result, after that we check if result divided with our start number (n) is int and we have simple solution. 因此,我们将其拆分,迭代并计算总结果,然后检查结果除以起始数字(n)是否为int并得到简单的解决方案。 Hope it helps.
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.