我在使用for循环时遇到了一些麻烦。我有while循环正常工作,但我需要帮助嵌套循环。循环的概念对我来说是相当新的,我不太明白我在代码中做了什么。任何帮助将不胜感激。
var number = parseInt(window.prompt("Enter number: ", ""));
var divisor;
var check;
var prime = true;
var num;
document.write("The factors of ", number, " are: </br>");
divisor = 1;
while (divisor <= number) {
check = number % divisor;
if (check == 0) {
document.write(divisor, " ");
if ((divisor != 1) && (divisor != number)) {
prime = false;
}
}
divisor = divisor + 1;
}
if (prime == true) {
document.write("<br>The number is prime");
} else {
document.write("<br> The number is composite");
}
答案 0 :(得分:0)
让你兴奋的东西。该程序用于检查素数。 for循环用作if-check但这可行。您还应该尝试使用函数来最小化代码。
var number = parseInt(window.prompt("Enter number: ", ""));
var result = isPrime(number);
function isPrime(number) {
var start = 2;
//USING WHILE
while (start <= Math.sqrt(number)) {
if (number % start++ < 1) return false;
}
return number > 1;
}
//USING FOR
for (;result;){
document.write("<br>The number is prime");
}
if(!result) {
document.write("<br>The number is NOT prime");
}
答案 1 :(得分:0)
作为一个新人,我想你可能需要在while循环中休息,因为你只是检查它是否是一次素数。就像那样:
if((divisor != 1) && (divisor != number)){
prime= false;
break;
}