Okay, so today I wanted to mess around with something called “Mertens’ Theorem” for prime numbers. I’d heard about it and it sounded kinda cool, so I figured, why not try to actually code something up related to it? No real reason, just for fun.
First, I needed to refresh my memory on what Mertens’ Theorem actually is. So, a quick search, you know. The bit I was interested in was the one about the product of (1 – 1/p) for primes p less than some number n. It’s supposed to get closer and closer to (e^(-gamma))/log(n) as n gets really big, where ‘gamma’ is this Euler-Mascheroni constant thing… around 0.577, apparently.
So, the plan? Write some simple code to calculate this product for primes up to a given number, and then compare it to the value predicted by Mertens’ thing. See how close we get.
I started by whipping up a quick function to check if a number is prime. Nothing fancy, just the usual “try dividing by numbers up to the square root” approach. It worked, that’s all that mattered.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n0.5) + 1):
if n % i == 0:
return False
return True
Next, I needed a function to actually do the Mertens’ product calculation. Again, super simple. Loop through numbers, check if they’re prime, and if they are, update the product.
def mertens_product(n):
product = 1.0
for i in range(2, n + 1):
if is_prime(i):
product = (1.0 - (1.0 / i))
return product
Finally, I wrote the main part. This bit set the ‘n’ value (I started with 100, then tried bigger numbers), calculated the Mertens’ product using my function, calculated the “predicted” value using that (e^(-gamma))/log(n) formula, and printed out both. I hardcoded the Euler-Mascheroni constant, because, lazy.
import math
euler_mascheroni = 0.5772156649 #lazy ...
n = 100 #changed the value several times
calculated_product = mertens_product(n)
predicted_value = (*(-euler_mascheroni)) / *(n)
print(f"Calculated Product (up to {n}): {calculated_product}")
print(f"Predicted Value: {predicted_value}")
print(f"the difference is : {abs(calculated_product - predicted_value)}")
I ran it for n=100, then n=1000, then n=10000. And… it kinda worked! I mean, the calculated product and the predicted value got closer as ‘n’ got bigger, which is what Mertens’ Theorem said should happen. It wasn’t exactly the same, obviously, because the theorem is about what happens as ‘n’ goes to infinity, and I wasn’t about to wait that long. But it was close enough to be satisfying. I saw the difference between calculated and predicted was getting smaller and smaller.
It’s not groundbreaking stuff, but it was a fun little experiment. And hey, I learned a tiny bit more about prime numbers, so that’s a win in my book.