pow Computes Modular Exponentiation With mod
The three-argument pow(x, y, mod) keeps intermediate values small where x**y would explode, and pow(x, -1, mod) computes a modular inverse or raises ValueError.
Code
# 三参 pow(x, y, mod) 是模幂运算:结果等价于 x**y % mod,但不构造大数
base, exponent, modulus = 7, 65537, 2**61 - 1
print("pow(x, y, mod) :", pow(base, exponent, modulus))
print("x**y % mod :", pow(base, exponent) % modulus)
# 典型场景:Diffie-Hellman 密钥交换的两端各自算公钥
p, g = 23, 5
a_secret, b_secret = 6, 15
a_public, b_public = pow(g, a_secret, p), pow(g, b_secret, p)
print("public keys :", a_public, b_public)
print("shared secret :", pow(a_public, b_secret, p), "==", pow(b_public, a_secret, p))
# 负指数:pow(x, -1, mod) 求模逆元(mod 必须与 x 互质)
print("inverse of 3 :", pow(3, -1, 11), "check:", 3 * pow(3, -1, 11) % 11)
# 不存在逆元时抛 ValueError
try:
pow(6, -1, 9)
except ValueError as exc:
print("no inverse :", exc)Output
Captured from a sandboxed run of this snippet in the build pipeline.
pow(x, y, mod) : 947640889622960979
x**y % mod : 947640889622960979
public keys : 8 19
shared secret : 2 == 2
inverse of 3 : 4 check: 1
no inverse : base is not invertible for the given modulusApplying it
The run emits 6 labeled sections — pow(x, y, mod) :, x**y % mod :, public keys :, shared secret :, inverse of 3 :, no inverse : — one per step.
Output is labeled for readability — expect lines prefixed with pow(x, y, mod) :, x**y % mod :, public keys :.
Statements that matter
except ValueError as exc:
print("no inverse :", exc)
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.X.509 PEM Certificate DecoderDecode X.509 PEM certificates in pure JavaScript using ASN.1 DER parsing to inspect subject, issuer, SANs, key usage, and SHA-256 fingerprints.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.