Back to the 2023 paper

Module III: Basics of Web Programming

20237m

Write a JavaScript to print all prime numbers from 1 to 100.

Worked SolutionAI Assisted

JavaScript: Prime Numbers from 1 to 100

A prime number is greater than 1 and has exactly two positive divisors: 1 and itself.

Program

for (let n = 2; n <= 100; n++) {
    let prime = true;

    for (let i = 2; i * i <= n; i++) {
        if (n % i === 0) {
            prime = false;
            break;
        }
    }

    if (prime) {
        console.log(n);
    }
}

Logic

  1. Start from 2 because 1 is not prime.
  2. Test each number up to 100.
  3. Check possible divisors from 2 through √n.
  4. If any divisor divides n exactly, it is not prime.
  5. Otherwise print the number.

Output: 2, 3, 5, 7, 11, 13, ... , 97.

Similar questions