Create a HTML page which accepts user input into the text field as integer between 10 and
120. When the user pressed the “Display” button, your function created in JavaScript should
able to display all prime integer between 1 and 120.
Example
Input Integer:
20
The Function should return:
1, 2, 3, 5, 7, 11, 13, 17, 19
function primeNumbers(){
var p;
var n = document.primeForm.primeText.value;
var d;
var x;
var prime;
var displayAll = 2 + " ";
for(p = 3; p <= n; p = p+2){
x = Math.sqrt(p);
prime=1;
for(d = 3; prime && (d <= x); d = d+2)
if((p%d) == 0)
prime = 0;
else
prime = 1;
if(prime == 1){
displayAll = displayAll + p + " ";
}
}
document.primeForm.primeArea.value = displayAll;
}
but it can display more than 120 🙁
The
forloop is where everything is happening. So if the value is outside of the range that you want, then don’t allow theforloop to execute. In order to do this, place anifstatement around theforloop.Since you only plan to use these numbers once, it doesn’t matter if you enter in the min/max directly in the
ifstatement or if you make a variable to hold the value. Most people suggest keeping all of your variables at the top in case you ever need to change the range: it’s easier to find them.On to the
ifstatement:nis the deciding factor in whether or not to execute theforloop. Here is the statement:if (n >= 10 && n <= 120) { insert the for loop here }. All you’re doing is checking if the input is greater than or equal to 10 AND checking that the input is less than or equal to 120.Note: if you don’t want anything displaying, then include the line right after the
forloop that is outputting the results in theifstatement.