Project Euler #27: Quadratic primes

  • + 0 comments
    import itertools
    
    def is_prime(x):
        if x % 2 == 0:
            return False
        for i in range(3, int(x**0.5) + 1, 2):
            if x % i == 0:
                return False
        return True
    
    def find_quadratic_primes(n):
        max_consecutive = 0
        best_solution = None
    
        for a, b in itertools.product(range(-n, n + 1), range(n + 1)):
            consecutive_primes = 0
            x = 0
    
            while True:
                abc = x**2 + a * x + b
    
                if abc < 0:  # As our required number must be at least positive
                    break
    
                if not is_prime(abc):
                    break
    
                x += 1
                consecutive_primes += 1
    
            if consecutive_primes > max_consecutive:
                best_solution = (a, b)
                max_consecutive = consecutive_primes
    
        return best_solution
    
    if __name__ == "__main__":
        n = int(input())
        solution = find_quadratic_primes(n)
        print(*solution)