Skip to content

Instantly share code, notes, and snippets.

@frostburn
Created February 7, 2026 09:17
Show Gist options
  • Select an option

  • Save frostburn/e7d311630a96cf5eb020a4b60846b0cc to your computer and use it in GitHub Desktop.

Select an option

Save frostburn/e7d311630a96cf5eb020a4b60846b0cc to your computer and use it in GitHub Desktop.
Bare-bones nth root of a prime
def pow(x, n):
"""
Bare-bones 'raise x to an integer power n'
"""
y = 1
for _ in range(n):
y *= x
return y
def nthroot(p, n):
"""
Minimal implementation of 'nth root of p'
Uses a fixed-point iteration for x ** -n = 1/p
"""
# Initial guess
x = 1.5
# Iteration
for _ in range(1000):
x += 1 / pow(x, n) - 1 / p
# Return the fixed point solution
return x
# Test with primes and their nth roots
for p in [2, 3, 5, 7, 11, 13]:
for n in range(2, 11):
reference = p ** (1 / n)
ours = nthroot(p, n)
print(f"{p} ** (1 / {n}) =", reference, "?=", ours, ": error =", ours - reference)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment