### [JavaScript] 利用 memoize 實作質數列舉程式

Memoize 是一種函式型程式的設計技巧, 基本上它的意思就是在函式中記錄計算的結果, 下一次再遇到同一個輸入參數時, 就可以把先前的計算結果直接取出, 不用再算一次。

``````from functools import cache

@cache
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

print(factorial(5))  # 120
print(factorial(5))  # 120 (從上次的計算結果中取出, 不必重新計算)``````

``````// 程式一
function isPrime(value) {
if (value > 2 && value % 2 == 0) // Rule out all even numbers
return false;
let check = value > 1; // 1 is not prime number
if (!isPrime.repos) { // Create the "answers" object
isPrime.repos= {};
}
if (isPrime.repos[value] !== undefined) { // If value exists in answers, return true
return isPrime.repos[value];
}
for (var i = 2; i < value/2; i++) { // Check if any known prime number can devide value, if not, it is a prime number
if (value % i === 0) {
check = false;
break;
}
}
return check? isPrime.repos[value] = check : false;
}``````

``````// 程式二
var timerTag = 0;
function enumeratePrimes(start, end) {
if (end <= start) {
console.warn('Parameter(s) is invalid.');
return;
}
console.log('Scanning', end-start, "numbers...");;
let iterated = 0;
if (start % 2 == 0) start++; // Discard the first even number
console.time(timerTag);
for (let i = start; i < end; i+=2) {
iterated++;
isPrime(i);
}
console.timeLog(timerTag++); // Measure durance
let itemsFound = Object.keys(isPrime.repos);
console.log(itemsFound);
console.log("Found", itemsFound.length, "items within", iterated, "iterations. (", itemsFound.length/(end-start)*100, "%)");
}``````

Dev 2Share @ 點部落