You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SageMath中如何基于Zmod模运算求解含平方根的表达式?

在Sage中用Zmod计算含平方根的模表达式

完全可以实现,无需额外第三方库,Sage自带的Zmod类就能处理这类需求,步骤如下:

1. 确认模下的平方根

首先在模9的环中找到7的所有平方根:

R = Zmod(9)
a = R(7)
# 获取所有平方根,返回[4, 5]
roots = a.sqrt(all=True)

验证:4²=16≡7 mod9,5²=25≡7 mod9,符合要求。

2. 代入表达式计算

针对自动生成的字符串表达式,有两种可靠的计算方式:

方式一:字符串替换+上下文求值

适合直接处理字符串形式的表达式:

expr_str = "-1 / sqrt(7) + 5"
R = Zmod(9)
a = R(7)
for root in a.sqrt(all=True):
    # 替换表达式中的sqrt(7)为当前根
    modified_expr = expr_str.replace("sqrt(7)", str(root))
    # 自定义上下文,用逆元实现模除法
    ctx = {"__builtins__": None, "/": lambda x, y: x * y.inverse_of_unit()}
    # 将数值转换为Zmod(9)元素后计算
    result = eval(modified_expr, ctx, {**ctx, **{num: R(num) for num in [-1,5]}})
    print(f"当sqrt(7)={root}时,结果为{result}")

方式二:符号变量代入(更安全)

避免使用eval,用符号计算的方式处理:

from sage.symbolic.ring import SR
R = Zmod(9)
# 定义符号变量代替sqrt(7)
x = SR.var('x')
expr = -1 / x + 5

a = R(7)
roots = a.sqrt(all=True)
for root in roots:
    # 将符号变量替换为模9中的根,计算结果
    res = expr.subs(x=R(root)).simplify()
    print(f"当sqrt(7)={root}时,结果为{res}")

两种方式都会输出:

当sqrt(7)=4时,结果为7
当sqrt(7)=5时,结果为3

关键说明

  • 当模数非素数时,sqrt(all=True)会返回该元素在模环中的所有平方根(存在时);
  • 模除法本质是乘以除数的逆元,需确保除数与模数互质(本例中4、5均与9互质,逆元存在)。

内容的提问来源于stack exchange,提问作者G.F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:19:58