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.

PythonSecurity Boundaries

Code

pythonsnippet
20 lines
# 三参 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 modulus

Applying 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

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.