Use native JS to judge prime numbers and find all prime numbers between 100 and 1000

Time:2021-3-25

Prime number:It is also called prime number, that is, a number greater than 1 and divisible only by 1 and itself

Step idea:
1. For traverses the loop to find other divisors
2. If the setting satisfies the condition (the counter starts from 2, excluding itself), the output will be interrupted

Demand 1: judge prime (quality) number

Function primenum (Num) {// declare named functions (formal parameters)
        Var flag = true; // variable storage = condition true
        For (VaR I = 2; I < num; I + +) {// for sets the loop body and iterates over whether there are other divisors (Prime: starting from 2, it can only be divided by 1 and itself)
            if (num % i === 0) {
                flag = false
                If break // exists, the execution is terminated and the output is returned
            }
        }
        Return flag // returns the true or false value of the variable
    }
    Var values = primenum (9) // test with the number 9
    console.log(values); // false

Requirement 2: find out all prime numbers between 100 and 1000

Var primenum = [] // the set of all prime numbers in the interval is an array
    var i = 0;
    Var count = 0; // calculates the number of primes
    for (i = 100; i <= 1000; i++) {
        var j = 0;
        For (J = 2; J < I; j + +) {// prime numbers need the condition "numbers greater than 1 and divisible only by 1 and itself"
            If (I% J = = = 0) {// can be divided by other numbers, then it is a non prime number and the traversal is terminated
                break;
            }
        }
        if (j >= i) { // ! JavaScript has no "block level scope", and the variable J still exists in the "external environment" after the assignment of the for loop!
            Count + +; // calculates the number of primes
            primeNum.push (i) // cumulative prime number appended
        }
    }
    console.log ('total prime '+ count +'number');
    console.log (primenum); // output target result array