13.7 Homework Assignment

Objective:

Students will create a JavaScript script that uses a loop to print all prime numbers between 1 and 50.

Task:

  • Write a JavaScript script that:

    • Uses a loop to check for prime numbers between 1 and 50.

    • Prints each prime number to the console.

Step-by-Step Instructions:

  1. Understanding Prime Numbers:

    • A prime number is a number greater than 1 that has no divisors other than 1 and itself.

    • Examples: 2, 3, 5, 7, 11, 13, etc.

    • Key Idea: For each number, check if it is divisible by any number other than 1 and itself. If not, it is prime.

  2. Create an HTML file (e.g., prime_numbers.html) and write the JavaScript code to find and print all prime numbers between 1 and 50.

    Example Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Prime Numbers between 1 and 50</title>
    </head>
    <body>
      <h1>Check the Console for Prime Numbers</h1>
    
      <script>
        // Function to check if a number is prime
        function isPrime(num) {
          if (num < 2) return false;
          for (let i = 2; i <= Math.sqrt(num); i++) {
            if (num % i === 0) {
              return false;  // Not prime if divisible by any number other than 1 or itself
            }
          }
          return true;  // Return true if it's prime
        }
    
        // Loop through numbers 1 to 20 and check for primes
        console.log("Prime numbers between 1 and 20:");
        for (let num = 1; num <= 20; num++) {
          if (isPrime(num)) {
            console.log(num);  // Print the prime number
          }
        }
      </script>
    </body>
    </html>
  3. Run the file in a browser:

    • Open the HTML file in a browser.

    • Use Developer Tools (F12 or right-click and select Inspect > Console) to view the prime numbers printed between 1 and 50.

Challenge:

  • Modify the script to count how many prime numbers are between 1 and 50 and print the count.

    Example for the Challenge:

    let primeCount = 0;
    
    for (let num = 1; num <= 50; num++) {
      if (isPrime(num)) {
        console.log(num);  // Print the prime number
        primeCount++;      // Increment the prime count
      }
    }
    
    console.log("Total number of primes between 1 and 50: " + primeCount);

Homework Submission:

  • Save your HTML file and submit it to the instructor.

  • Ensure the script correctly identifies and prints all prime numbers between 1 and 50, and includes a prime count if you take on the challenge.


Expected Outcome:

Students will:

  • Use loops and conditions effectively to find and print prime numbers.

  • Gain a deeper understanding of prime numbers and how to implement algorithms to check for them in JavaScript.

  • Be able to extend the solution to handle larger ranges or count prime numbers in a given range.

Last updated