问题
I am creating a external javascript file. This is for homework. What I am supposed to do is determine if the number that the user enters in is a prime number or not, and displays a message if it is a prime number or not. I have my code written, compiles and everything. But I am cannot seem to figure out with, no matter what number i enter in, the display message always says that that number is a prime number. Can anyone help? Here is my code:
var UI;
var TV;
var HITS;
UI = window.prompt("Enter a whole number to test as a prime number: \n", "0");
TV = parseInt(UI, 10);
var DD = TV; //still produces same error
HITS = 0;
while (DD > 0)
{
if (TV % DD === 0)
{
HITS++;
}
else
{
DD--;
}
}
if (HITS > 2)
{
document.write(UI + " is a NOT prime number");
}
else
{
document.write(UI + " is a prime number");
}
回答1:
I think you should set the var DD = TV;
after the TV = parseInt(UI, 10)
.
And you should decrement DD in the while loop, if you don't want it to be infinite.
Here is the code corrected
var UI = window.prompt("Enter a whole number to test as a prime number: \n", "0");
var TV = parseInt(UI, 10);
var HITS = 0;
var DD = TV;
while (DD > 0) {
if (TV % DD === 0) {
HITS++;
}
DD--;
}
if (HITS > 2) {
document.write(UI + " is a NOT prime number");
} else {
document.write(UI + " is a prime number");
}
来源:https://stackoverflow.com/questions/15837655/prime-number-determination-javascript