Created
February 7, 2026 09:17
-
-
Save frostburn/e7d311630a96cf5eb020a4b60846b0cc to your computer and use it in GitHub Desktop.
Bare-bones nth root of a prime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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