Sum All Primes-freecodecamp Algorithm topic

Source: Internet
Author: User

Sum All Primes

1. Requirements

    • Sum of prime numbers less than or equal to a given number.
    • Only 1 and its own two approximate numbers are called prime numbers. For example, 2 is a prime number, because it can only be divisible by 1 and 2. 1 is not a prime number because it can only be divisible by itself.

2. Ideas

    • To define the mark variable in a loop starting from 3 to no more than NUM, initially true
    • Determines whether I is a prime number in a two-layer cycle, no, turns mark to False
    • The end of a layer of loops when mark is true, adds a prime number that is less than or equal to a given value.

3. Code

function sumPrimes(num) {   var arr = [2];  var newNum = 2;    for (var i=3; i<=num; i++){    var mark = true;    for (var j=0; j<arr.length; j++){      if(i%arr[j] === 0){        mark = false;      }    }    if(mark){      arr.push(i);      newNum += i;    }  }  return newNum;//本代码只计算num大于2的情况}sumPrimes(9);

4. RELATED LINKS

    • Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for
    • Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Sum All Primes-freecodecamp Algorithm topic

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.