Prime Number Checker

In this example below you will see how to do a Prime Number Checker with some HTML / CSS and Javascript

Check to see if a number is a Prime number using trial division.

Thumbnail
This awesome code was written by SirDaev, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright SirDaev ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Prime Number Checker</title>
  <meta name="viewport" content="minimum-scale=1.0,maximum-scale=1.0,initial-scale=1.0,user-scalable=no"/>
<link href="https://fonts.googleapis.com/css?family=Droid+Sans:400,700" rel="stylesheet">
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="interface">
	<h1>Prime Number Checker</h1>
	<p>Enter a number to see if it is a Prime number.</p>
	<p>
		<input id="theNum" type="number" />
		<button id="check">Check!</button>
	</p>
	<p id="result"></p>
</div>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/SirDaev/prime-number-checker-wWNkxK */
*, *:before, *:after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  width: 100%;
  height: 100%;
}

body {
  position: relative;
  width: 100%;
  height: 100%;
  background: #815B6B; 
  font-family: 'Droid Sans', sans-serif;
  font-size: 16px;
	padding: 20px;
}

.interface {
  margin: 0 auto;
  overflow: auto;
  width: 900px;
  max-width: 100%;
  padding: 15px;
  background: #F5F5F5;
  color: #333;
  border: 1px solid #ccc;
	border-radius: 10px;
  box-shadow: 0 5px 20px -8px rgba(0,0,0,0.7);
}

h1, h2 {
	margin-bottom: 0.5em;
}

p {
	margin-bottom: 0.8em;
}

input {
	width: 150px;
}

.half {
	float: left;
	overflow: auto;
	width: 100%;
}

@media (min-width: 500px) {
	.half {
		width: 50%;
	}
	.half:first-of-type {
		padding-right: 20px;
	}
	.half:last-of-type {
		padding-left: 20px;
		border-left: 1px solid #333;
	}
}

/*Downloaded from https://www.codeseek.co/SirDaev/prime-number-checker-wWNkxK */
var check = document.getElementById('check');
var result = document.getElementById('result');

check.addEventListener('click', function() {
	var theNum = document.getElementById('theNum').value;
	var theResult = "";
	
	//Divide by 2 first. Anything over half cannot be divided in.
	//Besides theNum/2, how can I further simplify the equation?
	for(i=2;i<=(theNum/2);i++) {
		//Prevent memory issues
		if(theNum > 9999999) {
			theResult = "Sorry! Please enter a number less than 10,000,000 to avoid crashing the browser."
			break;
			//If a divisor is found
		} else if (theNum % i == 0) {
			theResult = "The number " + theNum + " is not a Prime number! The lowest number that " + theNum + " is divisible by is " + i + "."
			break;
			//If no divisor is found
		} else {
			theResult = "The number " + theNum + " is a Prime number!"
		}
	}
	result.innerHTML = theResult;
});

Comments