Question: ( e ) Implement a classical function to find the order of a modulo n where , a , n are inputs. what i have

(e) Implement a classical function to find the order of a modulo n where ,a,n are inputs.
what i have :
def gcd(m, n):
while n:
m, n = n, m % n
return m
def modular_exponentiate(a, k, n):
res =1
while k >0:
if k %2==1:
res =(res * a)% n
a =(a * a)% n
k //=2
return res
def find_order(a, n):
for r in range(1, n):
if modular_exponentiate(a, r, n)==1:
return r
return None
Write a function count_hits(n) that runs through all numbers a from 22 to 1n1, ignoring the ones for which (,)1GCD(a,n)1(in which case we will find a factor purely by chance) and counts the number of "hits" wherein a hit happens for a iff
what i have for this cell:
def gcd(m, n):
while n:
m, n = n, m % n
return m
def modular_exponentiate(a, k, n):
res =1
while k >0:
if k %2==1:
res =(res * a)% n
a =(a * a)% n
k //=2
return res
def find_order(a, n):
for r in range(1, n):
if modular_exponentiate(a, r, n)==1:
return r
return None
# Example usage:
print(find_order(4,7)) # This will return the order of 4 mod 7
def count_hits(n):
hits =0
for a in range(2, n):
if gcd(a, n)==1: # a and n must be relatively prime
r = find_order(a, n)
if r is not None and r %2==0: # Order must be even
if (modular_exponentiate(a, r //2, n)+1)% n ==0:
hits +=1
return hits
Cell that I can't change :
h15= count_hits(15)
print(f'count_hits(15)={h15}')
assert h15==6 # hits for 15 are 2,4,7,8,11,13
# note that \varphi(15)=2*4=8
print(f'Fraction of hits among relatively prime ={h15/(2*4)}')
h77= count_hits(77) # there should be 46 hits for 77
print(f'count_hits(77)={h77}')
assert h77==30
# note that \varphi(77)=6*10=60
print(f'Fraction of hits among relatively prime ={h77/(60)}')
h91= count_hits(91)
print(f'count_hits(91)={h91}')
assert h91==54
# note \varphi(91)=12*6=72
print(f'Fraction of hits among relatively prime ={h91/(72)}')
h111= count_hits(111) # there whould be 92 hits
print(f'count_hits(111)={h111}')
assert h111==54
# note \varphi(111)=36*2=72
print(f'Fraction of hits among relatively prime ={h111/(72)}')
h893= count_hits(893)
print(f'count_hits(893)={h893}')
assert h893==414
assertion error I get:
count_hits(15)=1
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[197], line 31 h15= count_hits(15)2 print(f'count_hits(15)={h15}')---->3 assert h15==6 # hits for 15 are 2,4,7,8,11,134 # note that \varphi(15)=2*4=85 print(f'Fraction of hits among relatively prime ={h15/(2*4)}') AssertionError:
thanks for your help!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!