方法一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var num = prompt("请输入你所要分解因数的正整数:", "1")
if(isNaN(num) == true){
num = prompt("请输入你所要分解因数的正整数:", "1")
}
if(num <= 0){
num = prompt("请输入你所要分解因数的正整数:", "1")
}
num = parseInt(num);
var numP = num;
var arrFactor = [];
var l = 0;
var arrPrem = [];
var k = 0;
for(var i = 2; i < num; i ++){
var isPrem = true;
for(var j = 2; j < i; j ++){
if(i % j == 0){
isPrem = false;
}
}
if(isPrem == true){
arrPrem[k] = i;
k ++;
}
}
for(var i = 0; i < arrPrem.length;){
if(num % arrPrem[i] == 0){
num = num / arrPrem[i];
arrFactor[l] = arrPrem[i];
l ++;
i = 0;
}else{
i ++;
}
}
document.write("正整数" + numP + "=");
if(arrFactor.length == 0){
document.write("你输入的数···")
}else{
for(var i = 0; i < arrFactor.length - 1; i ++){
document.write(arrFactor[i] + "×");
}
document.write(arrFactor[arrFactor.length - 1]);
}
</script>
</head>
<body>
</body>
</html>
方法二(优化)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var a = prompt("请输入你要分解的数:", "2");
a = 8;
b = a;
var num = [];
document.write(a + "=");
while (a > 1){
for(var i = 2; i < b; i ++){
if(a % i ==0){
a /= i;
num.push(i);
break;
}
}
}
document.write(num.join("×"));
</script>
</head>
<body> </body>
</html>