素数,需要一点帮助

时间:2017-12-07 00:38:23

标签: javascript arrays primes

背景资料:

所以我试图计算一个数字中的所有素数,然后总结它们。 sumPrimes(10)应该返回17,因为2 + 3 + 5 + 7 = 17

挑战在这里 - > https://www.freecodecamp.org/challenges/sum-all-primes

我添加了一些console.log只是为了表明发生了什么。

我的方法:

我这样做的方法是尝试在此处复制本教程,但代码为:https://youtu.be/FBbHzy7v2Kg?t=67

我尝试使用我的代码是将数字从2分成数组,直到你的数字(1不是素数)。 10看起来像[ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]。然后我使用另一个for循环与i从先前的数组arr中选择一个数字,将其添加到prime,然后从该数字中删除该数字的每一个数组(arr)使用单独的循环。当我回去再拿一个号码时,我们已经知道它是一个素数。

其余的是如果你不理解的话。

示例:

该数组的第一个数字是2.所以我将{2}添加到prime

  

素数的当前值:2

然后过滤掉任何倍数。由于我在j循环中按数字本身计数,我已经知道任何数字都是倍数。它还会从数组中删除我已经存在的素数及其所有多个数字,因此它永远不会被定义。

  

arr的当前值(希望如此):[ 3, 5, 7, 9]

等(继续使用3,5和7)。

出了什么问题?

它没有删除所有的倍数。我正在使用splice,我不认为它正确地删除了这个数字。帮助

请不要给我一些ES6答案然后走开。我想坚持我(视频的想法)。我不在乎你的答案有多短,只是我的错误。

repl - > https://repl.it/@John_Nicole/prime

function sumPrimes(num) {

    var prime = 0;
    var arr = [];


    for (let i = 2; i <= num; i++) {
        arr.push(i);
    } // turns into array
    console.log(arr)


    for (let i = 0; i < arr.length; i++) {
        var number = arr[i];
        console.log("Prime: "+prime+"+"+number)
        prime+=number


        for (var j = number; j <= arr.length; j+=number) {
          arr.splice(j)
        } // j

    } // i


   return "Final result: "+prime;
}

sumPrimes(10);

提前致谢:D

1 个答案:

答案 0 :(得分:1)

正如大家已经指出的那样,您对splice()的期望似乎不正确。在此处查看MDN文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

>>> [1,2,3].splice() # Input
>>> []               # Output

有两个问题:

  1. 该功能未正确删除值(来自arr
  2. 过滤器的循环逻辑没有考虑删除值时数组长度的变化
  3. 这是您使用splice删除值的方法:

    这会在您想要取出的索引之后的索引处创建一个数组副本

    arrayTail = arr.slice(j + 1);
    

    这将从开始到索引之前的所有元素从你想要取出的元素之前提取

    arrayHead = arr.splice(0,j);
    

    最后将两个部分合并在一起以获得过滤后的数组

    arr = arrayHead.concat(arrayTail);
    

    或者,您也可以使用Array.filter功能:

    arr = arr.filter(function(value){
        // Filter all values that are divisible by the prime
        return value % number != 0;
    });
    

    对于第二部分,请考虑:

    arr = [1,2,3,4,5,6,7,8,9];
    // You filter for multiples of 2
    // And that's okay because all the values are indices offset by 2
    arr = [1,2,3,5,9];
    // You filter for multiples of 3
    arr[2] == 3
    arr[4] == 9
    // But the multiples of 3 are no longer offset by 3
    

    因此,不要对索引很聪明,只需像往常一样循环遍历数组的其余部分,然后检查当前值是否为素数的倍数。

    if (arr[j] % number == 0) {
        ... your splice code
    }
    

    现在,这可能是未经请求的,听起来你只是在学习编程。我强烈建议养成使用完整变量名的习惯,以便于阅读。并且还包括许多注释,以突出您尝试通过该编码块实现的逻辑。

    希望你能找到一个很好的例子:

    function sumPrimes(num) {
    
        var currentPrime = 0;
        var arr = [];
        var sumOfPrimes = 0;
    
        // Create an array of potential primes
        for (let i = 2; i <= num; i++) {
            arr.push(i);
        }
        console.log("Prime array", arr);
    
        // For every value in the array, remove any future multiples of it
        for (let i = 0; i < arr.length; i++) {
            var currentPrime = arr[i];
            console.log("Prime: " + currentPrime);
    
            sumOfPrimes += currentPrime;
            console.log("Sum of Primes: " + sumOfPrimes);
    
            // Remove multiples of prime
            // Start at the next value in the array
            // And loop till the end
            for (let j = i + 1; j < arr.length; j++) {
                // If the current value is a multiple of
                // the prime, then remove it
                if (arr[j] % currentPrime == 0) {
                    arrayTail = arr.slice(j + 1);
                    arr = arr.splice(0,j).concat(arrayTail);
                    j -= 1;
                    // Since you removed an element, you need to
                    // move the index back so it doesn't skip
                    // any checks
                }
            }
    
            console.log("Filtered array for ", currentPrime, arr);
    
        }
    
       return "Final result: " + sumOfPrimes;
    }