finding sum of prime numbers under 250

后端 未结 8 875
忘了有多久
忘了有多久 2020-12-19 18:52
var sum = 0

for (i = 0; i < 250; i++) {

    function checkIfPrime() {

        for (factor = 2; factor < i; factor++) {
            if (i % factor = 0) {
            


        
8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-19 19:41

    Here is a simple way of looping through array and implementing the sieve of Eratosthenes...

    function sumPrimes(num) {
      var t, v = [],
        w = [],
        x = [],
        y = [],
        z = 0;
      //enumerating Vee array starts at 2 as first prime number
      for (let a = 2; a <= num; a++) {
        v.push(a)
      }
      //creating a moving loop by splicing its first index
      for (let i = 0; i < v.length; i) { //ensure all items spliced 
        t = v[i]; // t as prime to be removed from Vee array 
        x.push(t); // x storage of primes
        z += t //  total of peculiar primes
        w.push(v.splice(i, 1)) //tested to move all one by one
        // prompt(v) //tested that v loses its v[i] every iteration
        //= now trying to remove others using remainder (%) vs prime t
        for (let vi in v) {
          v[vi] % t === 0 ? y.push(v.splice(vi, 1)) : ""; //recursive removal of composite items by prime t
        }
      }
      return z // returns sum of primes
    }
    sumPrimes(250);

    You generate the array beginning with 2 as first prime, You sieve the array removing items by the remainder of prime using % === 0. The you loop through the remaining array by using the next prime until the last remaining prime is pushed to the prime arrays. Add all primes to get the Sum.

提交回复
热议问题