JavaScript中Project Euler最大质因数问题排查及数组最大值咨询
Hey there! Let's tackle your two questions one by one—first that stubborn bug with the 29 log, then the array max question.
Why isn't the 29 console.log firing & num never hits 1?
The most likely culprit here is an issue with your checkIfPrime function, or a small logic error in how you're updating num during factorization. Let's break down common pitfalls:
Broken prime check function
IfcheckIfPrime(29)is returningfalsewhen it should returntrue, your code will skip the log and never updatenumto 1. Double-check your prime check logic:- Did you handle edge cases (like 2, the only even prime)?
- Are you looping up to
Math.sqrt(n)(instead ofn/2orn—both work but sqrt is more efficient)? - Is your return logic reversed? For example, returning
trueas soon as a non-divisor is found (wrong) instead of returningfalsewhen a divisor is found, thentrueafter the loop finishes (correct).
Here's a solid working version for reference:
function checkIfPrime(n) { if (n <= 1) return false; if (n === 2) return true; if (n % 2 === 0) return false; // Skip even numbers after 2 for (let i = 3; i <= Math.sqrt(n); i += 2) { if (n % i === 0) return false; } return true; }Non-integer
numvalues
If at any pointnumbecomes a floating-point number (instead of an integer),num % imight never equal 0, even wheniis a valid factor. Make sure you're using integer division—replacenum = num / iwithnum = Math.floor(num / i)or usenum = num / ionly when you know the division is exact (which it should be for prime factors, but better safe than sorry).Loop condition misstep
Double-check your outer loop (the one that runs untilnum === 1). If it's written aswhile (num > 2)or something similar instead ofwhile (num > 1), it'll stop before processing the final prime factor (29 in this case).
Correct ways to get the max value from an integer array
You've got a few reliable options here, depending on your use case:
Simplest:
Math.max(...array)
Spread the array intoMath.max—it's concise and easy to read:const factors = [5, 7, 13, 29]; const largest = Math.max(...factors); // Returns 29Note: This can hit a limit if your array is extremely large (like 10k+ elements), but it's perfect for Project Euler problems.
Most robust:
Array.reduce()
Usereduceto iterate and track the maximum value—great for large arrays or if you want more control:const factors = [5, 7, 13, 29]; const largest = factors.reduce((currentMax, num) => { return num > currentMax ? num : currentMax; }, -Infinity); // Start with -Infinity to handle negative numbers tooManual loop (for learning purposes)
If you want to understand the underlying logic, a simple loop works too:function getArrayMax(arr) { if (arr.length === 0) return null; // Handle empty array case let max = arr[0]; for (const num of arr) { if (num > max) { max = num; } } return max; }
内容的提问来源于stack exchange,提问作者Canovice

