Skip to content

Update euler-0027.cpp #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 35 additions & 48 deletions euler-0027.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,63 +33,50 @@

#include <iostream>

// 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;
}