finding sum of prime numbers under 250

后端 未结 8 827
忘了有多久
忘了有多久 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:24

    So i had to face a similar challenge and here is my solution, i hope you find it helpful:

     function sumPrimes(num) {
    
          // determine if a number is prime
          function isPrime(n) {
            if (n === 2) return true;
            if (n === 3) return true;
            if (n % 2 === 0) return false;
            if (n % 3 === 0) return false;
    
            var  i = 5;
            var  w = 2;
            while (i * i <= n) {
                if (n % i === 0) {
                    return false;
                }
                i += w;
                w = 6 - w;
            }
            return true;
          }
    
          // subtract 1 for 'not being prime' in my context
          var sum = isPrime(num) ? num - 1 : -1;
    
          for (var x = 0; x < num; x++) {
            if (isPrime(x) === true) {
              sum += x;
            }
          }
    
          return sum;
        }
    

提交回复
热议问题