Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

python实现模幂的优化算法 #111

Open
yanghailong-git opened this issue Aug 21, 2024 · 0 comments
Open

python实现模幂的优化算法 #111

yanghailong-git opened this issue Aug 21, 2024 · 0 comments

Comments

@yanghailong-git
Copy link

yanghailong-git commented Aug 21, 2024

def mod_pow(base, exponent, modulus):
    result = 1

    # 将指数展开为二进制形式,从高位到低位逐位处理
    while exponent > 0:
        # 如果当前位是1,则乘上当前的 base,然后取模
        if exponent % 2 == 1:
            result = (result * base) % modulus
        # 将 base 平方,然后取模
        base = (base * base) % modulus
        # 右移一位,相当于除以2
        exponent //= 2

    return result

# 示例:计算 (7^5) % 13
a = 7
c = 5
n = 13
result = mod_pow(a, c, n)
print(f"{a}^{c} mod {n} = {result}")
# 7^5 mod 13 = 11

上面的算法是从低位到高位吧?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant