Prime Numbers up to an Input Number

Table of Contents

Prime Numbers up to a Limit Top ↑

Prime numbers have exactly two positive factors: 1 and the number itself. The first five primes are 2, 3, 5, 7, and 11.

Generate Prime Numbers Top ↑

Enter a limit to display all primes from 2 through that value, inclusive. The original page said “up to” while its loop stopped before the input value; the updated demo makes the behavior match the heading.

Output here

Complete Working Source Top ↑

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>JavaScript Prime Numbers up to a Limit</title></head>
<body>
<label for="t1">Show prime numbers up to</label>
<div class="col-sm-4 px-0"><input type="number" class="form-control" id="t1" min="2" max="100000" step="1"></div>
<button type="button" class="btn btn-primary btn-sm mt-2" id="b1">Submit</button>
<div id="d1" class="alert alert-success mt-3" style="word-break:break-word" aria-live="polite">Output here</div>
<script>
const input = document.getElementById("t1");
const output = document.getElementById("d1");
const submitButton = document.getElementById("b1");

function isPrime(number) {
  if (number < 2) return false;
  if (number === 2) return true;
  if (number % 2 === 0) return false;

  for (let divisor = 3; divisor <= Math.sqrt(number); divisor += 2) {
    if (number % divisor === 0) return false;
  }
  return true;
}

function showPrimes() {
  const limit = Number(input.value.trim());

  if (!Number.isInteger(limit) || limit < 2 || limit > 100000) {
    output.textContent = "Enter an integer from 2 to 100,000.";
    return;
  }

  const primes = [];
  for (let number = 2; number <= limit; number += 1) {
    if (isPrime(number)) primes.push(number);
  }

  output.textContent = `Prime numbers up to ${limit}: ${primes.join(", ")}`;
}

submitButton.addEventListener("click", showPrimes);
</script>
</body>
</html>

How the Algorithm Works Top ↑

Each candidate number is checked by the reusable isPrime() function. Even values greater than 2 are rejected immediately, and odd divisors are tested only through the candidate's square root.

Number.isInteger()Check whether a parsed value is an integer.
parseInt()Convert a string to an integer where that conversion is appropriate.

Next lower value of any decimal number JavaScript Basic JavaScript variable

JavaScript Math Reference




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer