• JavaScript prime number program
  • In this example will learn about how to find the number is prime or not.
  • WHATS IS PRIME NUMBER
  • A number greater than 1 with exactly two factors is called prime number.
  • Number which is divisible by 1 and itself is prime number. If it is divisible by any other number(other than 1 and itself) then it's not a prime number.
    • Consider an example of number 5 ,Which has only two factors  1 and 5. This means 5 is a prime number. Lets take one more example Number 6, which has more than two factors, i.e 1,2,3. This means 6 is not a prime number.
    • The first ten prime numbers are 2,3,5,7,11,13,17,19,23,29.
    • Note: It should be noted that 1 is non-prime number, because in the above defination already mentioned A number greater than 1 with 2 factors called prime number..

  • Here we have simple program to print the prime numbers in java script.
JavaScript program to check a number is prime number or not.

  1. <html>
  2.     <head>
  3. <script>
  4.     // javascript program to check the number is prime or not.
  5.     // prime number program in javascript
  6.     // javascript prime number program
  7.     // take input from the user
  8. const x = parseInt(prompt("Enter a number to check prime or not: "));
  9. let isPrimeNumber=true;

  10. // check if number is equal to 1
  11. if (x  === 1) {
  12.     alert("1 is neither prime nor composite number.");
  13. }

  14. // checking  if  number is greater than one or not

  15. else if (x  > 1) {

  16.     // iterating from 2 to number -1 (leaving 1 and itself )
  17.     for (let i = 2; i < x ; i++) {
  18.         if (x  % i == 0) {
  19.             isPrimeNumber = false;
  20.             break;
  21.         }
  22.     }

  23.     if (isPrimeNumber) {
  24.         alert(`${x } is a prime number`);
  25.     } else {
  26.         alert(`${x } is not a prime number`);
  27.     }
  28. }

  29. // check if number is less than 1
  30. else {
  31.     console.log("The number is not a prime number.");
  32. }
  33. </script>
  34.     </head>
  35.     <body>

  36.     </body>
  37. </html>




Output:
javascript prime number
javascript prime number program


Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu