Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

prime number program in javascript

Tags: number
  • 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.    
  2.     // javascript program to check the number is prime or not.
  3.     // prime number program in javascript
  4.     // javascript prime number program
  5.     // take input from the user
  6. const x = parseInt(prompt("Enter a number to check prime or not: "));
  7. let isPrimeNumber=true;

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

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

  13. else if (x  > 1) {

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

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

  27. // check if number is less than 1
  28. else {
  29.     console.log("The number is not a prime number.");
  30. }
  31.    
  32.    

  33.    




Output:




This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

prime number program in javascript

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×