May 2, 2025

Twin Prime Constant (C++)

Twin Prime Constant 0.66016.....that there is such a constant means there is a pattern

DownloadOpen

The twin prime constant is defined as the limit of the sum of the reciprocals of twin primes, given by the formula: C2​=p≥3∏​(1−(p−1)21​)​, where p ranges over all prime numbers such that p and p+2 are both prime.

It's value is C2​≈0.660161815846869573927812110014 and the code below quickly converges to that number even for a low number of primes.

The fact that this number exists and is stable means there has to be a pattern in primes.

#include <iostream>
#include <vector>
#include <cmath>

// Function to check if a number is prime
bool is_prime(int n) {
    if (n < 2) return false;
    if (n == 2 || n == 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) return false;
    }
    return true;
}

// Function to compute the twin prime constant
double compute_twin_prime_constant(int limit) {
    double C2 = 1.0; // Start with multiplicative identity

    for (int p = 3; p <= limit; p += 2) {
        if (is_prime(p)) {
            double factor = 1.0 - 1.0 / ((p - 1) * (p - 1));
            C2 *= factor;
        }
    }

    return C2;
}

int main() {
    int limit;
    std::cout << "Enter the upper limit for prime numbers: ";
    std::cin >> limit;

    if (limit < 3) {
        std::cout << "Please enter a limit greater than or equal to 3." << std::endl;
        return 1;
    }

    double result = compute_twin_prime_constant(limit);

    std::cout.precision(15);
    std::cout << "Approximated Twin Prime Constant (C2) with limit " << limit << ": " 
              << result << std::endl;
    std::cout << "Known value (approx): 0.6601618158468" << std::endl;

    return 0;
}