https://projecteuler.net/problem=46
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
$9 = 7 + 2×1^2$
$15 = 7 + 2×2^2$
$21 = 3 + 2×3^2$
$25 = 7 + 2×3^2$
$27 = 19 + 2×2^2$
$33 = 31 + 2×1^2$
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
Okay, we reuse Fermat's test and brute force. Easy.
def expmod(base, exp, m):
if exp == 0:
return 1
if (exp % 2 == 0):
return (expmod(base, exp // 2, m) ** 2 % m)
return (base * expmod(base, exp - 1, m) % m)
def fermat_test(n):
a = n - 3
return expmod(a, n, n) == a
def twice_square(n):
return 2 * n * n
n_max = 10000
twice_squares = [twice_square(n) for n in range(1, n_max + 1)]
def test_conjecture(n):
for ts in twice_squares:
if ts > n:
return False
if fermat_test(n - ts):
return True
assert(test_conjecture(33))
for n in range(3, n_max + 1, 2):
if not fermat_test(n) and test_conjecture(n) == False:
s = n
print(s)
assert(s == 5777)