Prime Number Program in JavaScript

Advertisements

Prev Tutorial Next Tutorial

Prime Number Program in JavaScript

Using JavaScript you can easily write any programming code, Here we write one of the most popular program Prime Number Program in JavaScript. To perform this task we need for loop and if else condition.

Prime Number Program in JavaScript

<html>
<head>
<script type="text/javascript">

function calcPrimeNumber()
{

 var beginNum = parseInt(document.numbers.firstNum.value);
 var endNum = parseInt(document.numbers.secondNum.value);
 var primeNumbs = new Array();
 var ctr = beginNum;
 while(ctr<=endNum)
{
if(isPrime(ctr)==true)
 {
  primeNumbs[primeNumbs.length] = ctr;
  }
  ctr = ctr+1;
}
 if (primeNumbs.length == 0)
{
document.getElementById('output_content').innerHTML = "There were no prime no within the range.";
 }
 else
 {
 outputPrimeNums(primeNumbs);
  }
}
function isPrime(num)
{
var flag = true;
for(var i=2; i<=Math.ceil(num/2); i++)
 {
if((num%i)==0)
{
flag = false;
 break;
}
}
return flag;    
 }

 function outputPrimeNums(primes)
{
 var html = "<h2>Prime Numbers</h2>";
 for (i=0;i<primes.length;i++){
  html += primes[i] + "<br/>";
 }
 document.getElementById('output_content').innerHTML = html;
 }

</script>
</head>
<body>
<form name="numbers">
Beginning Number: <input type="text" name="firstNum" />
End Number: <input type="text" name="secondNum" />
<input type="button" value="Find Prime Numbers" onclick="calcPrimeNumber()" />

</form>
<div id="output_content">
</div>
</body>
</html>

Output

Start Number:

End Number:


Prev Tutorial Next Tutorial

Advertisements

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet


For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements