Prime Number Determination Javascript

不羁的心 提交于 2019-12-17 21:10:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!