數論:任意數求原根(python代碼)


# 用輾轉相除求最大公因子
def gcd(a,b):
    r=a%b
    while(r!=0):
        a=b
        b=r
        r=a%b
    return b

# 歐拉函數-暴力循環版
def euler(a):
    count=0
    for i in range(1,a):
        if gcd(a,i)==1:
            count+=1
    return count

def order(a,n,b):
#   輸出b在mod(a)中的階
#   n是mod(a)群的階
    p=1
    while(p<=n and (b**p%a!=1)):
          p+=1
    if p<=n:
          return p
    else:
          return -1

# 求任意數原根
def primitive_root(a):
    n=euler(a)
    prim=[]
    for b in range(2,a):
        if order(a,n,b)==n:
            prim.append(b)
    print(prim)

測試結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM