0

I am a beginner at Javascript and we were given this challenge but it's too hard. Please give me a chance to know the answer and explain so I could understand it better.

   <!DOCTYPE html>
    <html>
    <body>

    <script>
      function doAction(){
        //clears the output
        document.getElementById("output").innerHTML = "";

        //gets the value from the text field with id input1 and stores it in variable num1
        var num1 = document.getElementById("input1").value;


        //HINT: loop through some finite number and check whether they are prime
        //You can create a function out of the CheckPrime exercise and use that to check if a number 
    is Prime

        //for loop the numbers until you satisfy the num1
        sampleFunction(num1);



        //Challenges:
        //validate if the input are numbers. Hint: Check out isNaN() function
        //Validate the input to only be less than equal 200
      }

      function sampleFunction(x){
        window.alert("Sample Function" + x);
      }
    </script>

    <h2>Prime Numbers Printer</h2>
    Prints the first N prime numbers. Only try up to 200.
    <br/>
    <br/>
    Input1: <input type="text" id="input1"/>
    <button type="button" onclick="doAction()">
     Print Prime</button>
    <br/>
    <br/>
    Result:
    <p id="output"></p>

    </body>
    </html> 

I tried to search for a prime formula and implemented it to a for loop but it did not work it seems.

blank
  • 3
  • 1

1 Answers1

0

You can use the following way:

<!DOCTYPE html>
    <html>
    <body>

    <script>
      function doAction(){

max = document.getElementById('input1').value;
//primeNumTill(max);
//console.log(primeNumTill(max));
document.getElementById('output').innerHTML = primeNumTill(max);
}


function primeNumTill(max)
{//console.log(max);
    var store  = [], i, j, primes = [];
    for(i = 2; i <= max; ++i) 
    {
        if (!store [i]) 
          {
            primes.push(i);
            for (j = i << 1; j <= max; j += i) 
            {
                store[j] = true;
            }
        }
    }
    return primes;
}
    </script>

    <h2>Prime Numbers Printer</h2>
    Prints the first N prime numbers. Only try up to 200.
    <br/>
    <br/>
    Input1: <input type="text" id="input1"/>
    <button type="button" onclick="doAction()">
     Print Prime</button>
    <br/>
    <br/>
    Result:
    <p id="output"></p>

    </body>
    </html>
MSQ
  • 489
  • 5
  • 15