def number_odd_period(N): total = 0 for n in tqdm(range(1, N + 1)): continued_fraction = continued_fraction_periodic(0, 1, n) if len(continued_fraction) > 1 and len(continued_fraction[1]) % 2 == 1: total += 1 return total
def get_lowest_cf(p, d, x): #find convergent cfs cfp = continued_fraction_periodic(p, d) fracs = list(continued_fraction_convergents(cfp)) #get list of denominators denoms = [int(f.q) for f in fracs] try: val = max([num for num in denoms if num < x]) except ValueError: raise ('List is empty!') return val
def wiener_attack_rsa(public_key): N = public_key[0] e = public_key[1] # cf = continued_fraction_periodic(e, N) convergents = list(continued_fraction_convergents(cf)) polynomial_power = 0 for i in convergents: polynomial_power += 1 n, d = fraction(i) if n != 0: exp = ((e * d) - 1) / n n2, d2 = fraction(exp) #if d2 == 1: factors = (np.roots([1, -((N - n2) + 1), N])) return factors
def viner_attack(e, n): # Find period of fraction drob = continued_fraction_periodic(e, n) # Find all convergent fraction k_1/d_1, k_i/d_i, k_n/d_n # Calculation based on Euler recurrent formulas convergents = [] convergents.append((drob[0], 1)) convergents.append((drob[0] * drob[1] + 1, drob[1])) i = 2 while i < len(drob): p = convergents[i - 1][0] * drob[i] + convergents[i - 2][0] q = convergents[i - 1][1] * drob[i] + convergents[i - 2][1] convergents.append((p, q)) i = i + 1 i = 0 for (k, d) in convergents: # check if d is actually the key # We are try to calculate: f_i = (e*d_i - 1) / k_i # 1. So k_i != 0 # 2. We don't want irrational f_i, so check (e * d - 1) % k == 0 if k != 0 and (e * d - 1) % k == 0: f = (e * d - 1) // k # Original equation: x^2 - ((N - f) + 1)*x + N = 0 # So we are replace s = ((N - f) + 1) s = n - f + 1 # check if the equation x^2 - s*x + n = 0 # has integer roots discr = s * s - 4 * n # Discriminant exist if (discr >= 0): # Find t = sqrt(discr) t = _is_perfect_square(discr) if t != -1 and (s + t) % 2 == 0: return int(d)
def main(): # generate a list of square numbers to skip for convenience n = 1 squares = set() while n**2 <= MAXN: squares.add(n**2) n+=1 N = 1 count = 0 while N <= MAXN: if N not in squares: if len(continued_fraction_periodic(0,1,N)[1]) % 2 == 1: count += 1 # print(N, "counted") # else: #print(N, "not counted") N += 1 print(count)
def test_p064(): assert continued_fraction_periodic(0, 1, 23) == [4, [1, 3, 1, 8]] assert number_odd_period(13) == 4
from sympy.ntheory.continued_fraction import continued_fraction_periodic print continued_fraction_periodic(3, 2, 7)