diff --git a/euler-0027.cpp b/euler-0027.cpp index 61702dc..7a6b523 100644 --- a/euler-0027.cpp +++ b/euler-0027.cpp @@ -33,63 +33,50 @@ #include -// return true if x is prime +// Function to check if a number is prime bool isPrime(int x) { - // reject invalid input - if (x <= 1) - return false; - - // process all potential divisors - for (int factor = 2; factor*factor <= x; factor++) - if (x % factor == 0) - return false; - - // no such divisor found, it's a prime number - return true; + if (x <= 1) return false; + for (int factor = 2; factor * factor <= x; factor++) + if (x % factor == 0) return false; + return true; } int main() { - // upper and lower limit of the coefficients - int limit; - std::cin >> limit; - // make sure it's a positive number - if (limit < 0) - limit = -limit; + int limit; + std::cin >> limit; + + // Ensure limit is positive + if (limit < 0) limit = -limit; + + int bestA = 0, bestB = 0; + int maxConsecutivePrimes = 0; - // keep track of best sequence: - // number of generated primes - unsigned int consecutive = 0; - // its coefficients - int bestA = 0; - int bestB = 0; + // Iterate over coefficients a and b + for (int a = -limit; a <= limit; a++) { + for (int b = 2; b <= limit; b++) { // Only check positive primes for b + if (!isPrime(b)) continue; // Skip non-prime values of b - // simple brute-force approach - for (int a = -limit; a <= +limit; a++) - for (int b = -limit; b <= +limit; b++) - { - // count number of consecutive prime numbers - unsigned int length = 0; - while (isPrime(length * length + a * length + b)) - length++; + int length = 0; - // better than before ? - if (consecutive < length) - { - consecutive = length; - bestA = a; - bestB = b; - } + // Count consecutive primes + while (isPrime(length * length + a * length + b)) { + length++; + } + + // Update best coefficients if a longer sequence is found + if (length > maxConsecutivePrimes) { + maxConsecutivePrimes = length; + bestA = a; + bestB = b; + } + } } -#define ORIGINAL -#ifdef ORIGINAL - // print a*b - std::cout << (bestA * bestB) << std::endl; -#else - // print best factors - std::cout << bestA << " " << bestB << std::endl; -#endif - return 0; + // Print best coefficients + std::cout << bestA << " " << bestB << std::endl; + + return 0; } +