使用 JavaScript 查找所有和数等于输入数的可能的素数对
问题
我们要求编写一个接收数字 n 的 JavaScript 函数。我们的函数应返回和数等于 n 且它们都是素数的所有此类数对的数组。
示例
以下是代码 -
const num = 26; const isPrime = (n) => { if (n % 2 === 0) return false; let sqrtn = Math.sqrt(n)+1; for (let i=3; i < sqrtn; i+=2) { if (n % i === 0) return false; } return true; } const primeList = (a) => { if (isPrime(a)) return a; else return false; }; const generateNumbers = (n) => { let num = (n % 2 === 0) ? (n -1) : n; let list = [] for (let i = num; i > 3; i-=2) list.push(i); list.push(3,1); return list; } const calculate = (num, list, results) => { if (list.length === 0) return results; let item = list.shift(); let itemPairIndex = list.indexOf(num - item); if (itemPairIndex !== -1) { let itemPair = list.splice(itemPairIndex,1) results.push(item+"+"+itemPair); } return calculate(num, list, results); } const findprimeSum = (num) => { const pairs = []; const list = generateNumbers(num).filter(primeList); return calculate(num, list, []); } console.log(findprimeSum(num));
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
输出
[ '23+3', '19+7' ]
广告