JavaScript determines whether a number is prime

Source: Internet
Author: User

Determine if the user is entering a prime number
Const ReadLine = require ("Readline-sync"); Console.log ("Please enter a number:"= readline.question ()-0;  while (IsNaN (num) | | num <= 0) {    console.log ("input error, please re-enter")    ; = Readline.question ()-0;}  while (num = = 1) {    console.log ("1 is neither prime nor composite");     = Readline.question ()-0;    }
Method one: from 2 to num-1 number, find can be divisible by num number, find that num is not prime, otherwise it is prime
Let a = 0; // for temporary counting  for (Let i = 2; i < num; i++) {   if (num% i = = 0) {       console.log (num+ "not Prime");       A++       ;  Break ;   }} if (A = = 0)    {+ "is prime");}
Method Two: The number from 2 to NUM, the number that can be divisible by num, if this number equals num,num is prime, otherwise it is not prime
 for (Let i = 2; I <= num; i++) {    if(num% i = = 0)       {if (num = = i) {           + "is prime");       } Else {           + "not prime number")           ;  Break ;       }    }}

Method Three: from 1 to num, look for numbers divisible by num, find the Count 1 times, the final number if 2,num is prime, otherwise it is not prime

Let B = 0;  for (Let i = 1; I <= num; i++) {    if (num% i = = 0) {        b+ +;    }} if (b = = 2)    {+ "is prime");} Else {    + "not prime number");}



JavaScript determines whether a number is prime

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.