Judge whether a number is prime

Prime number refers to the natural number with no other factors except 1 and itself in the natural number greater than 1.

1, I n the tagging method, the initial value of flag is true. When n%i === 0 (1 < I < n), it means that n is not a prime number. At this time, the flag value is false and the cycle is terminated; when n%i! =When 0, the value of flag is always true, and the output n is prime.

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <script>
        function num(n){
            for(var i=2;i<n;i++){
              var flag=true
                if(n%i===0){
                    flag=false
                    document.write(n+'Not prime numbers.')
                    break
                }
            }
            if(flag){
                    document.write(n+'Prime number')
                }
        }
        num(prompt('Please enter a number'))
    </script>
</body>
</html>

 

2, Count method, calculate the times of n%i === 0 (1 < = I < = n), when the count value is 2, it means that n is prime, when n > 2, it means that n is not prime.

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <title>Document</title>
 7 </head>
 8 <body>
 9     <script>
10         function num(n){
11             var count=0
12             for(var i=1;i<=n;i++){
13                 if(n%i===0){
14                     count++
15                 }
16             }
17             if(count===2){
18                     document.write(n+'Prime number')
19                 }
20                 else if(count>2){
21                     document.write(n+'Not prime numbers.')
22                 }
23         }
24         num(prompt('Please enter a number'))
25     </script>
26 </body>
27 </html>

Output all prime numbers of an interval: https://www.cnblogs.com/strongerPian/p/12635632.html

Tags: Javascript

Posted on Sun, 05 Apr 2020 08:16:24 -0700 by keyurshah