Javascript Program to Check whether Number is Prime or Not

[6182 views]



What is Prime Number?

A prime number is a number which is divisible by only two numbers: 1 and itself. So, if any number is divisible by any other number, it is not a prime number.

Javascript Program to Check whether Number is Prime or Not
function checkPrime(no){ for(x=2;x<no/2;x++){ if(no%x==0){ break; } } if(x>=(no/2)) return true; else return false; } function showMessage(Result){ var answer=Result(13); // passed 13 as a number if(answer==true) console.log("Is prime"); else console.log("Not Prime"); } showMessage(checkPrime);

When you run the program, the output will be:

Is prime

In the above program, checkPrime function takes 'no' as parameter to check whether it is prime or not. In the loop x value changes from 2 to (no/2). In every iteration, we check if the number is divisible by x, if yes directly come out of the loop and obviously value of x will be less than (no/2), else continue with the iteration until the last element i.e (no/2). After that we just check if the value of x is greater than (no/2), if yes return true else return false.

In showMessage Function, we pass the Value to be checked using Result(13) and store the boolean result in 'answer' variable. Then based on the value returned by checkPrime function, we just print either "Is Prime" or "Not Prime"

        



Facing Programming Errors. Get Answer within 48 hours:





Giving is the Master Key to Success, in all applications of human life.


Comments



Search
For Sponsored Advertisement OR Freelance Programming Article Submission, Contact us at atechdailyweb@gmail.com
Recommended Deals Ends in







Quiz Challenge:
Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags

    Check if number is prime using JS