Skip to content

Commit 714bdab

Browse files
committed
feat: add Quadratic Primes algorithm and tests (Problem 27)
1 parent c6192d7 commit 714bdab

File tree

1 file changed

+13
-23
lines changed

1 file changed

+13
-23
lines changed

Diff for: Project-Euler/Problem027.js

+13-23
Original file line numberDiff line numberDiff line change
@@ -17,45 +17,35 @@
1717
* and the product of coefficients a and b.
1818
*/
1919
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-
*/
2620
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
3024
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
3326
}
34-
return true // No divisors found, so it is prime
27+
return true
3528
}
3629

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
3932

4033
for (let a = -999; a < 1000; a++) {
4134
for (let b = -1000; b <= 1000; b++) {
4235
let n = 0
43-
let consecutivePrimes = 0
4436
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
4839
n++
4940
}
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
5344
}
5445
}
5546
}
5647

57-
return { maxPrimes, product } // Return the results
48+
return { maxPrimes, product }
5849
}
5950

60-
// Exporting the main function for use in other modules
6151
export { findMaxConsecutivePrimes }

0 commit comments

Comments
 (0)