|
| 1 | +/** |
| 2 | + * Problem - Quadratic Primes |
| 3 | + * |
| 4 | + * @see {@link https://projecteuler.net/problem=27} |
| 5 | + * |
| 6 | + * The quadratic expression n^2 + an + b, where |a| < 1000 and |b| ≤ 1000, |
| 7 | + * produces a positive prime for consecutive values of n, starting with n = 0. |
| 8 | + * Find the product of the coefficients, a and b, for the quadratic expression that |
| 9 | + * produces the maximum number of primes for consecutive values of n. |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * Main function to find the coefficients a and b that produce the maximum number |
| 14 | + * of consecutive primes for the quadratic expression n^2 + an + b. |
| 15 | + * |
| 16 | + * @returns {{maxPrimes: number, product: number}} An object containing the maximum number of primes |
| 17 | + * and the product of coefficients a and b. |
| 18 | + */ |
| 19 | +function findMaxConsecutivePrimes() { |
| 20 | + /** |
| 21 | + * Checks if a number is prime. |
| 22 | + * |
| 23 | + * @param {number} n - The number to check for primality. |
| 24 | + * @returns {boolean} True if n is a prime number, false otherwise. |
| 25 | + */ |
| 26 | + function isPrime(n) { |
| 27 | + if (n < 2) return false // 0 and 1 are not prime numbers |
| 28 | + if (n === 2) return true // 2 is a prime number |
| 29 | + if (n % 2 === 0) return false // Exclude even numbers |
| 30 | + for (let i = 3; i <= Math.sqrt(n); i += 2) { |
| 31 | + // Check odd divisors only |
| 32 | + if (n % i === 0) return false // Divisible by i, so not prime |
| 33 | + } |
| 34 | + return true // No divisors found, so it is prime |
| 35 | + } |
| 36 | + |
| 37 | + let maxPrimes = 0 // Store the maximum number of primes found |
| 38 | + let product = 0 // Store the product of coefficients a and b |
| 39 | + |
| 40 | + for (let a = -999; a < 1000; a++) { |
| 41 | + for (let b = -1000; b <= 1000; b++) { |
| 42 | + let n = 0 |
| 43 | + let consecutivePrimes = 0 |
| 44 | + while (true) { |
| 45 | + const result = n * n + a * n + b // Evaluate the quadratic expression |
| 46 | + if (result < 0 || !isPrime(result)) break // Stop if the result is negative or not prime |
| 47 | + consecutivePrimes++ |
| 48 | + n++ |
| 49 | + } |
| 50 | + if (consecutivePrimes > maxPrimes) { |
| 51 | + maxPrimes = consecutivePrimes |
| 52 | + product = a * b // Calculate product of coefficients a and b |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return { maxPrimes, product } // Return the results |
| 58 | +} |
| 59 | + |
| 60 | +// Exporting the main function for use in other modules |
| 61 | +export { findMaxConsecutivePrimes } |
0 commit comments