我需要创建一个计算器,用户输入一个数字,然后计算给定数字的因子,立方体和平方。
以下是我正在使用的代码..我不知道如何计算出这个因素。任何意见,将不胜感激。
document.getElementById('calculate').addEventListener('click', estimateTotal);
function estimateTotal(event) {
event.preventDefault();
var initial2 = document.getElementById('initial').value;
document.getElementById('factor').value = 0;
document.getElementById('sqaure').value = initial2 * initial2;
document.getElementById('cube').value = initial2 * initial2 * initial2;
}

<form id="calculator" method="POST">
<p>Please enter a number between 0 and 50 <input name="initial" id="initial" type="text" size="20" required><button id="calculate">Calculate</button></p>
<p>The Factorial of your number is: <input name="factor" id="factor" class="factor" type="text" size="20"></p>
<p>The Square of your number is:<input name="sqaure" id="sqaure" class="sqaure" type="text" size="20"></p>
<p>The Cube of your number is:<input name="cube" id="cube" class="cube" type="text" size="20"></p>
</form>
&#13;
答案 0 :(得分:2)
**recursive JavaScript function factor(n)**
**Check this link:** **http://www.javascripter.net/math/primes/factorization.htm**
function factor(n) {
if (isNaN(n) || !isFinite(n) || n%1!=0 || n==0) return ''+n;
if (n<0) return '-'+factor(-n);
var minFactor = leastFactor(n);
if (n==minFactor) return ''+n;
return minFactor+'*'+factor(n/minFactor);
}
答案 1 :(得分:1)
尝试使用因子和因子
document.getElementById('calculate').addEventListener('click', estimateTotal);
function estimateTotal(event) {
event.preventDefault();
var initial2 = document.getElementById('initial').value;
document.getElementById('Factorial').value = fact(initial2);
document.getElementById('factor').value = factors(initial2);
document.getElementById('sqaure').value = initial2 * initial2;
document.getElementById('cube').value = initial2 * initial2 * initial2;
}
function fact(n)
{
if(n == 0)
return 1;
else
return (n*fact(n-1));
}
function factors(num)
{
var
n_factors = [],
i;
for (i = 1; i <= Math.floor(Math.sqrt(num)); i += 1)
if (num % i === 0)
{
n_factors.push(i);
if (num / i !== i)
n_factors.push(num / i);
}
n_factors.sort(function(a, b){return a - b;}); // numeric sort
return n_factors;
}
<p>Please enter a number between 0 and 50 <input name="initial" id="initial" type="text" size="20" required><button id="calculate">Calculate</button></p>
<p>The Factorial of your number is: <input name="factor" id="Factorial" class="factor" type="text" size="20"></p>
<p>The Factor of your number is: <input name="factor" id="factor" class="factor" type="text" size="20"></p>
<p>The Sqaure of your number is:<input name="sqaure" id="sqaure" class="sqaure" type="text" size="20"></p>
<p>The Cube of your number is:<input name="cube" id="cube" class="cube" type="text" size="20"></p>