我的目标是创建一个程序,检查用户输入是否是一个完美的数字。它验证了输入的数字。如果输入是一个完美的数字,我想打印出每个除数。我尝试使用这种方法:
{
for(int number=2; number <= 10000 ; number++)
perfect(number);
return 0;
}
void perfect(int number)
{
int total = 0;
for (int i = 1; i < number; i++)
{
if (number % i == 0)
total += i;
}
if (number == total)
{
for (int x = 1; x < number; x++)
{
if (number % x == 0)
cout << x << " + ";
}
cout << " = " << number << endl;
}
}
然而,我无法达到预期的效果。我是javascript的新手,我正在努力以正确的方式插入代码。有没有人建议我如何才能获得理想的效果?这是我已编写的代码:
function check_prime() {
var input = document.getElementById("enteredNumber").value;
var number = parseInt(input);
if (isNaN(number)) {
alert("Oops! Please enter a valid number.");
document.getElementById("enteredNumber").value="";
document.getElementById("result").innerHTML = "";
document.getElementById("enteredNumber").focus();
}
else if (input.length === 0) {
alert("Please enter a number.");
document.getElementById("enteredNumber").focus();
}
else if (!isNaN(number)) {
if (is_perfect(number)) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number." ;
}
else {
document.getElementById("answer").innerHTML = "I'm sorry. " + number + " is not a perfect number. Try Again.";
}
}
else {
document.getElementById("answer").innerHTML = "Please enter a number.";
}
}
function is_perfect(number)
{
var temp = 0;
for(var i=1;i<=number/2;i++)
{
if(number%i === 0)
{
temp += i;
}
}
if(temp === number)
{
return true;
}
else
{
return false;
}
}
function clear_textbox(){
document.getElementById("answer").innerHTML = "";
document.getElementById("enteredNumber").value="";
document.getElementById("enteredNumber").focus();
}
答案 0 :(得分:1)
我建议修改你的is_perfect()
函数,如果数字是完美的,则返回一系列除数,如果数字不完美则返回null
。然后,当输入是完美数字时,调用代码可以显示除数。
function is_perfect(number) {
var temp = 0;
var divisors = [];
for(var i=1;i<=number/2;i++) {
if (number%i === 0) {
divisors.push(i);
temp += i;
}
}
return temp === number ? divisors : null;
}
然后:
var divisors = is_perfect(number);
if (divisors) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number.";
// display the divisors somewhere; the alert is just for show
alert("Divisors: " + divisors.toString());
} else {
...
}
[注意:在此答案的早期版本中,我已将temp
初始化为1,将divisors
初始化为[1]
,并在2开始循环,理论上1是永远是一个除数。遗憾的是,这是错误的,因为1不是正确的除数1.修订版is_perfect()
现在返回null
,参数为1而不是{ {1}}。另一种解决办法是明确测试案例[1]
,但那个更丑陋(如果效率更高一点,因为它可以避免一次number === 1
评估)。]