<!DOCTYPE html>
<html>
<head>
<title>prime</title>
<script>
function assert(value, desc) {
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
document.getElementById("results").appendChild(li);
}
function isPrime(value) {
if (value <= 1) {
console.log('抱歉,素数的讨论范围是大于一的自然数')
return alert('抱歉,素数的讨论范围是大于一的自然数')
}
if (!isPrime.cach) {
console.log("创建缓存对象");
isPrime.cach = {};
}
debugger;
if (isPrime.cach[value] !== undefined) {
console.log("缓存里里可以查到");
return isPrime.cach[value]
}
let prime = true;;
for (var i = 2, len = Math.pow(value, 1 / 2); i <= len; i++) {
if (value % i === 0) {
prime = false;
break;
}
}
return isPrime.cach[value] = prime;
}
console.log(isPrime(6))
console.log(isPrime(6))
window.onload = function () {
assert(true, "The test suite is running.");
assert(false, "Fail!");
assert(isPrime(5), "5 is prime!");
assert(isPrime(5), "The answer was cached!");
};
</script>
<style>
#results li.pass {
color: green;
}
#results li.fail {
color: red;
}
</style>
</head>
<body>
<ul id="results"></ul>
</body>
</html>
结果如下:

本文介绍了一种使用JavaScript实现的素数判断算法,并利用缓存机制提高重复调用效率。通过创建缓存对象存储已计算过的素数值,避免了重复计算,显著提升了性能。文章还展示了如何在网页中通过脚本运行该算法并显示测试结果。
636

被折叠的 条评论
为什么被折叠?



