範圍內素數 - JavaScript
我們需要編寫一個 JavaScript 函式,其中輸入兩個數字(比如 a 和 b),並返回 a 和 b 之間的質數總數(包括 a 和 b,如果它們是質數)。
例如 −
If a = 2, and b = 21, the prime numbers between them are 2, 3, 5, 7, 11, 13, 17, 19
它們的計數是 8。我們的函式應返回 8。
讓我們為此函式編寫程式碼 −
示例
以下是程式碼 −
const isPrime = num => { let count = 2; while(count < (num / 2)+1){ if(num % count !== 0){ count++; continue; }; return false; }; return true; }; const primeBetween = (a, b) => { let count = 0; for(let i = Math.min(a, b); i <= Math.max(a, b); i++){ if(isPrime(i)){ count++; }; }; return count; }; console.log(primeBetween(2, 21));
輸出
以下是控制檯中的輸出 −
8
廣告