gpt4 book ai didi

python - 适当的卡迈克尔函数

转载 作者:行者123 更新时间:2023-11-28 19:05:20 35 4
gpt4 key购买 nike

我正在为 RSA 算法创建所有必要的函数。不幸的是,我似乎无法制作适当的 Carmichael 函数。

这些是我写的函数:

def gcd(a, b):  # Greatest Common Divisor Generator (Euclidean Algorithm)
while b != 0: # While remainder exists
t = b # Initially r[k-1]
b = a % t # Initially r[k] = r[k-2] mod r[k-1] (where r[k-2] is a)
a = t # Predecessor of remainder (b)
return a

def phi(n): # Leonard Euler's Totient Function
y = 0
for k in range(1, n + 1): # Phi(+n) is the number of integers k in the range (1 <= k >= n)...
if gcd(n, k) == 1: # for which gcd(n, k) = 1
y += 1
return y

def carmichael(n): # Robert Daniel Carmichael's Function
y = (phi(n) * 1/2) if (n > 4 and ((n & (n - 1)) == 0)) else phi(n) # phi(n) * 1/2 if 2^x = n, else phi(n) * 1
return y

我正在使用 totient 函数生成数字。据我所知,有一个简单的规则,如果数字是 2 的幂且大于 4,则其质数的数量应减半,否则等于 phi(n)。

上面的规则在我的代码中完美运行,例如,如果输入值为 8,则结果如下:

phi(8) = 4
carmichael(8) = 2

但问题是,出于某种原因,Carmichael 函数也会将其他数字减半,例如,如果输入为 12,这就是我的函数返回的内容:

phi(12) = 4
carmichael(12) = 4

但它应该是这样的:

phi(12) = 4
carmichael(12) = 2

为什么会这样?也许非质数奇数应该区别对待?有什么我需要添加到我的函数中的吗?

谢谢!

最佳答案

首先我们创建 gcd计算 2 个数的最大公约数的函数,稍后我们将在 lambda 函数中用到它。

 def gcd(a,b):
while (a>0):
b=b%a
(a,b)=(b,a)
return b

然后我们看看 carmichael 函数是如何工作的。

Let n be a positive integer. Then λ(n) is defined to be the smallest positive integer k such that
a^k≡1(mod n)
for all a such that gcd(a,n)=1.

请注意,我们正在寻找 k , a 的值一旦我们有 n 就确定了。


现在我们用默认条件初始化函数

n=int(n)
k=2
a=1
alist=[]

要查找所有 a 值,我们使用 gcd(a,n)=1测试 an 的最大公约数是否为 1,这意味着它们互质。
如果没有,a++
如果gcd(a,n)==1 ,我们将这个值存储到 a 的列表中并测试下一个 a 直到我们测试所有 a<=n

        while not ((gcd(a,n))==1):
a=a+1

while ((gcd(a,n))==1) & (a<=n) :
alist.append(a)
a=a+1
while not ((gcd(a,n))==1):
a=a+1

好的,现在我们在列表alist中有了所有的a,回头看看定义

the smallest positive integer k such that
a^k≡1(mod n)

首先我们统计a的个数,也就是alist的长度
timer=len(alist)
然后我们使用
if (a**k)%n==1:
测试这个 k 是否使 a^k≡1(mod n)对于列表中的所有值。我们构造一个循环

for a in alist:
if (a**k)%n==1:
timer=timer-1
if timer <0:
break
pass
else:
timer=len(alist)
k=k+1

测试从2开始的所有k个数,如果不符合要求,我们做k=k+1


现在我们的整个函数如下

    def carmichael(n):
n=int(n)
k=2
a=1
alist=[]

while not ((gcd(a,n))==1):
a=a+1

while ((gcd(a,n))==1) & (a<=n) :
alist.append(a)
a=a+1
while not ((gcd(a,n))==1):
a=a+1

timer=len(alist)
while timer>=0:
for a in alist:
if (a**k)%n==1:
timer=timer-1
if timer <0:
break
pass
else:
timer=len(alist)
k=k+1
return k

关于python - 适当的卡迈克尔函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47761383/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com