|
17 | 17 | * and the product of coefficients a and b. |
18 | 18 | */ |
19 | 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 | 20 | 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 |
| 21 | + if (n < 2) return false |
| 22 | + if (n === 2) return true |
| 23 | + if (n % 2 === 0) return false |
30 | 24 | 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 |
| 25 | + if (n % i === 0) return false |
33 | 26 | } |
34 | | - return true // No divisors found, so it is prime |
| 27 | + return true |
35 | 28 | } |
36 | 29 |
|
37 | | - let maxPrimes = 0 // Store the maximum number of primes found |
38 | | - let product = 0 // Store the product of coefficients a and b |
| 30 | + let maxPrimes = 0 |
| 31 | + let product = 0 |
39 | 32 |
|
40 | 33 | for (let a = -999; a < 1000; a++) { |
41 | 34 | for (let b = -1000; b <= 1000; b++) { |
42 | 35 | let n = 0 |
43 | | - let consecutivePrimes = 0 |
44 | 36 | 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++ |
| 37 | + const result = n * n + a * n + b |
| 38 | + if (result < 0 || !isPrime(result)) break |
48 | 39 | n++ |
49 | 40 | } |
50 | | - if (consecutivePrimes > maxPrimes) { |
51 | | - maxPrimes = consecutivePrimes |
52 | | - product = a * b // Calculate product of coefficients a and b |
| 41 | + if (n > maxPrimes) { |
| 42 | + maxPrimes = n |
| 43 | + product = a * b |
53 | 44 | } |
54 | 45 | } |
55 | 46 | } |
56 | 47 |
|
57 | | - return { maxPrimes, product } // Return the results |
| 48 | + return { maxPrimes, product } |
58 | 49 | } |
59 | 50 |
|
60 | | -// Exporting the main function for use in other modules |
61 | 51 | export { findMaxConsecutivePrimes } |
0 commit comments