Prime: Also known as prime numbers, in natural numbers greater than 1, there are no other factors except 1 and itself.
That is, the number that can only be divisible by 1 and itself is a prime number. This is a question that I often do when I get started with programming.
// Determine whether a number is a prime number (prime number). (A number that can only be divisible by 1 and itself, or: except 1 and itself, no other number can be divisible by it)//Method 1:function test(){ //1, input var num = parseInt(("num").value);//9 //2. Business logic for(var i=2;i<=num-1;i++){//i=7 num=7 if(num%i==0){ break; } } if(i>num-1){ alert(num+"It's a prime number"); }else{ alert(num+"It's a composite number"); } }
//Method 2:function test(){ //1, input var num = parseInt(("num").value);//9 //2. Business logic var isSu=true;//isSu: indicates whether it is a prime number; assuming it is a prime number; for(var i=2;i<=num-1;i++){ if(num%i==0){ isSu = false; break; } } if(isSu==true){ alert(num+"It's a prime number"); }else{ alert(num+"It's a composite number"); } }
//Method 3:function test(){ //1, input var num = parseInt(("num").value);//9 //2. Business logic var count=0;//Record the number of divisors for(var i=2;i<=num-1;i++){// if(num%i==0){ count++; break; } } if(count==0){ //3, output alert(num+"It's a prime number"); }else{ alert(num+"It's a composite number"); } }
Summarize
This is the end of this article about how to judge whether a number is a prime number in JS. This is the end. For more related JS. content, please search my previous article or continue browsing the related articles below. I hope everyone will support me in the future!