def brent_factorise(n, iterations=None): """ Perform Brent's variant of Pollard's rho factorization algorithm to attempt to find a non-trivial factor of the given number number, n. If iterations > 0, return None if no factors are found within its range """ y, c, m = (randint(1, n - 1) for _ in range(3)) r, q, g = 1, 1, 1 i = 0 while g == 1: x = y for _ in range(r): y = _pollard_brent_func(c, n, y) k = 0 while k < r and g == 1: ys = y for _ in range(min(m, r - k)): y = _pollard_brent_func(c, n, y) q = (q * abs(x - y)) % n g = helpers.gcd(q, n) k += m r *= 2 if iterations: i += 1 if i == iterations: return None if g == n: while True: ys = _pollard_brent_func(c, n, ys) g = helpers.gcd(abs(x - ys), n) if g > 1: break return g
def g(n): if n == 4: return 13 else: if gcd(n, g(n-1)) != 1: print n, g(n - 1), gcd(n, g(n - 1)) return g(n - 1) + gcd(n, g(n - 1))
def attempt_to_solve(a, n, b, m): d = gcd(n, m) reduced_a = a % d reduced_b = b % d if reduced_a != reduced_b: return 0 else: n_pf = pfs[n] m_pf = pfs[m] L = [] for (prime, power) in n_pf.items(): if prime in m_pf and m_pf[prime] >= power: # do nothing for now r = 1 else: L.append((a % (prime**power), prime**power)) for (prime, power) in m_pf.items(): if prime in n_pf and n_pf[prime] > power: # do nothing r = 1 else: L.append((b % (prime**power), prime**power)) answer = crt(L) return answer % (n * m / d)
def attempt_to_solve(a, n, b, m): d = gcd(n, m) reduced_a = a % d reduced_b = b % d if reduced_a != reduced_b: return 0 else: n_pf = pfs[n] m_pf = pfs[m] L = [] for (prime, power) in n_pf.items(): if prime in m_pf and m_pf[prime] >= power: # do nothing for now r = 1 else: L.append((a % (prime**power), prime**power)) for (prime, power) in m_pf.items(): if prime in n_pf and n_pf[prime] > power: # do nothing r = 1 else: L.append((b % (prime**power), prime**power)) answer = crt(L) return answer % (n * m / d)
def compute_at_value(fib_sequence_recurring_part, x, modulus): total = 0 if is_terminating_expression(x, modulus): pow_of_x = 1 while (x**pow_of_x) % modulus != 0: total += fib_sequence_recurring_part[pow_of_x] * pow( x, pow_of_x, modulus) total %= modulus pow_of_x += 1 return total else: # Need to do a little math to determine periodicity of solution fib_period = len(fib_sequence_recurring_part) pow_period = 1 while pow(x, pow_period, modulus) != 1: pow_period += 1 total_period = fib_period * pow_period / gcd(fib_period, pow_period) for pow_of_x in xrange(total_period): total += fib_sequence_recurring_part[pow_of_x % fib_period] * pow( x, pow_of_x, modulus) total %= modulus total *= 10**15 / total_period total %= modulus remaining_portion = 10**15 % total_period for pow_of_x in xrange(remaining_portion + 1): total += fib_sequence_recurring_part[pow_of_x % fib_period] * pow( x, pow_of_x, modulus) total %= modulus return total
def get_periodic_fraction(n): l = [] num_part_1 = 1 num_part_2 = -int(n**0.5) den = 1 l.append([int(n**0.5),den,num_part_1,num_part_2]) while(l.count(l[-1]) == 1): den,num_part_1,num_part_2 = num_part_1**2*n-num_part_2**2,num_part_1*den,-den*num_part_2 l.append([int((num_part_1*n**0.5+num_part_2)/den),den,num_part_1,num_part_2]) #print(l) num_part_2 -= den*l[-1][0] d = gcd(gcd(abs(den),abs(num_part_1)),gcd(abs(den),abs(num_part_2))) den,num_part_1,num_part_2 = int(den/d),int(num_part_1/d),int(num_part_2/d) #print(den,num_part_1,num_part_2) x = [l[i][0] for i in range(len(l)-1)] return(x)
def distance(self, observation): dist = np.inf for obs in self.observations: d = gcd(obs.ra, obs.dec, observation.ra, observation.dec) if d < dist: dist = d return dist
def f(n): total = 0 for a in range(1, n + 1): for b in range(1, n + 1 - a): if gcd(a, b) != 1: total += 1 total += n - 1 return total * 6
def get_periodic_fraction(n): l = [] num_part_1 = 1 num_part_2 = -int(n**0.5) den = 1 l.append([int(n**0.5), den, num_part_1, num_part_2]) while (l.count(l[-1]) == 1): den, num_part_1, num_part_2 = num_part_1**2 * n - num_part_2**2, num_part_1 * den, -den * num_part_2 l.append([ int((num_part_1 * n**0.5 + num_part_2) / den), den, num_part_1, num_part_2 ]) #print(l) num_part_2 -= den * l[-1][0] d = gcd(gcd(abs(den), abs(num_part_1)), gcd(abs(den), abs(num_part_2))) den, num_part_1, num_part_2 = int(den / d), int(num_part_1 / d), int( num_part_2 / d) #print(den,num_part_1,num_part_2) x = [l[i][0] for i in range(len(l) - 1)] return (x)
def from_primes(cls, p: int, q: int, public_exp: int = DEFAULT_EXPONENT): n = p * q m = lcm(p - 1, q - 1) e = public_exp if gcd(m, e) > 1: raise ValueError(f'Prime cannot be one more than a multiple of'\ 'chosen exponent {e}') d = multiplicative_inverse(e, m) return cls(n, e, d)
def Pollard_rho(n,N): def H(x): return (x*x + 1)%N x = random.randint(1, N - 1) d = gcd(x,N) if d != 1: print('Factor found: ', d) y = x B = 2**(math.ceil(n/2)) print('try 2^(n/2) = ', B, ' steps') i = 0 while i < B: x = H(x) y = H(H(y)) p = gcd((x - y)%N, N) if p != 1 and p != 0: print('Factor found: ', p) return i += 1 print('Fail')
def solve(solution_vec, smooth_nums, xlist, N): solution_nums = [smooth_nums[i] for i in solution_vec] x_nums = [xlist[i] for i in solution_vec] Asquare = 1 for n in solution_nums: Asquare *= n b = 1 for n in x_nums: b *= n a = helpers.isqrt(Asquare) factor = helpers.gcd(b - a, N) return factor
def kasiski(text, substr_len=3): substr_with_pos = {} for i, sym in enumerate(text): substr = text[i:i + substr_len] if substr in substr_with_pos.keys(): substr_with_pos[substr].append(i) else: substr_with_pos[substr] = [i] possible_key_lengths = [] for substr, positions in substr_with_pos.items(): if len(positions) < 3: continue distances = [ positions[i + 1] - positions[i] for i in range(len(positions) - 1) ] expected_length = helpers.gcd(distances) possible_key_lengths.append(expected_length) return helpers.choose_most_common_value(possible_key_lengths)
''' from math import sqrt from helpers import gcd limit = 10**9 sqrootlimit = int(sqrt(limit)) total = 0 for a in range(1, sqrootlimit + 1): if a % 10 == 0: print a for b in range(a, sqrootlimit + 1): if a * b % (a + b) == 0: c = a * b / (a + b) if gcd(gcd(a, b), c) == 1: x = a * a y = b * b z = c * c max_allowable_multiple = limit / y # print x,y,z total += max_allowable_multiple * (max_allowable_multiple + 1) * (x + y + z) / 2 print total ''' 315306518862563689 [Finished in 134.3s] '''
from helpers import gcd from helpers import sieve primes = sieve(100000) #answer is the first number n such that ord_{9n}(10) is >1000000 def o(n): answer = 1 while(pow(10,answer,9*n) != 1): answer += 1 return(answer) done = False count = 3 answer_count = 0 print(o(91)) l = [] while(not done): if(gcd(10,count) == 1 and count % o(count) == 1 and count not in primes): print('answer #%s = %s'%(answer_count+1,count)) answer_count += 1 l.append(count) if(answer_count == 25): print('done') break count += 1 print('final answer:',sum(l))
from helpers import gcd fractions = [] bigNum,bigDen = 1,1 for num in range(10,100): numerator = str(num) for a in range(1,10): if not '0' in numerator: if float(numerator)/int(str(a) + numerator[1]) == float(numerator[0])/a: fractions.append([num, int(str(a) + numerator[1])]) if float(numerator)/int(numerator[1] + str(a)) == float(numerator[0])/a: fractions.append([num, int(numerator[1] + str(a))]) if float(numerator)/int(str(a) + numerator[0]) == float(numerator[1])/a: fractions.append([num, int(str(a) + numerator[0])]) if float(numerator)/int(numerator[0] + str(a)) == float(numerator[1])/a: fractions.append([num, int(numerator[0] + str(a))]) for fraction in fractions: if fraction[0] < fraction[1]: bigNum *= fraction[0] bigDen *= fraction[1] print(bigDen/gcd(bigDen,bigNum))
def number_of_lattice_points(a, b, c, d): twice_area = (b + d) * (a + c) num_boundary = gcd(a, b) + gcd(b, c) + gcd(c, d) + gcd(d, a) interior_lattice_points = (twice_area - num_boundary) / 2 + 1 return interior_lattice_points
def f(m, n): total = 0 for k in range(1, n + 1): # print k total += fact(m * gcd(n, k)) / (fact(gcd(n, k))**m) return total / (m * n)
d = x^2 + y^2 ''' from helpers import gcd from math import sqrt c_limit = 10**8 d_limit = int(sqrt(c_limit)) xy_limit = int(sqrt(d_limit)) total = 0 for y in range(1, xy_limit + 1): #if y % 10 == 0: # print y for x in range(y + 1, xy_limit + 1, 2): if gcd(x, y) == 1: m = x * x - y * y n = 2 * x * y d = x * x + y * y if gcd(m, n) == 1 and (m % 2 == 0 or n % 2 == 0) and d * d <= c_limit: a = abs(m * m - n * n) b = 2 * m * n area = a * b / 2 if area % 28 != 0 and area % 6 != 0: total += 1 print total ''' LOL IT'S 0
from helpers import gcd count = 0 for d in range(1,12001): n = int(d/3)+1 while n < d/2: print(d,n) if(gcd(n,d) == 1): count += 1 n += 1 print(count)
from helpers import gcd def o(n): answer = 1 while(pow(10,answer,9*n) != 1): answer += 1 return(answer) done = False count = 1000000 while(not done): if(gcd(10,count) == 1 and o(count) > 1000000): print('answer = ',count) done = True break count += 1
def f(m, n): total = 0 for k in range(1, n + 1): # print k total += fact(m * gcd(n, k)) / (fact(gcd(n, k))**m) return total / (m * n)
''' from helpers import gcd, memoize @memoize def g(n): if n == 4: return 13 else: if gcd(n, g(n-1)) != 1: print n, g(n - 1), gcd(n, g(n - 1)) return g(n - 1) + gcd(n, g(n - 1)) a = {n : g(n) - n for n in range(4, 1000)} b = [k for (k, v) in a.items() if k+1 in a and v != a[k + 1]] print b ''' Seems like it might just be brute force while storing the current difference g(n) - n. Let f(n) = g(n) - n. Then f(n) = g(n-1) + gcd(n, g(n - 1)) - n = f(n-1) - 1 + gcd(n, f(n-1) + n - 1). = f(n-1) - 1 + gcd(n, f(n-1) - 1) So f(n) is constant unless gcd(n, f(n-1) - 1) is not 1. This suggests we prime factorize f(n-1) - 1 at each step
def get_num_of_cuboids(m,n,k): a = k*(m**2-n**2) b = 2*k*m*n if(a > 2*lim or b > 2*lim): return(0) return(f(a,b)) print(get_num_of_cuboids(10,1,1)) print(get_num_of_cuboids(2,1,26)) m = 2 n = 1 count = 0 while(m < 500): while(n < m): if(gcd(m,n) == 1): #if(get_num_of_cuboids(m,n,1) > 0): #print(m,n) k = 1 while(get_num_of_cuboids(m,n,k) > 0): #print('get_num_of_cuboids(%s,%s,%s)=%s'%(m,n,k,get_num_of_cuboids(m,n,k))) count += get_num_of_cuboids(m,n,k) k += 1 n += 2 m += 1 if(m % 2 == 0): n = 1 else: n = 2
''' from math import sqrt from helpers import gcd limit = 10**9 sqrootlimit = int(sqrt(limit)) total = 0 for a in range(1, sqrootlimit + 1): if a % 10 == 0: print a for b in range(a, sqrootlimit + 1): if a * b % (a + b) == 0: c = a * b / (a + b) if gcd(gcd(a, b), c) == 1: x = a * a y = b * b z = c * c max_allowable_multiple = limit / y # print x,y,z total += max_allowable_multiple * (max_allowable_multiple + 1) * (x + y + z) / 2 print total ''' 315306518862563689 [Finished in 134.3s] '''
from helpers import gcd lim = 1500001 def get_p(m,n): return(2*m*(m+n)) l = [0 for i in range(lim)] for m in range(2000): n = 1 while(n < m and get_p(m,n) < lim): if(gcd(m,n) == 1 and m%2 != n%2): f = 1 while(f*get_p(m,n) < lim): #print(f,m,n) l[f*get_p(m,n)] += 1 f += 1 n += 1 count = 0 for i in l: if(i == 1): count += 1 #print(l) print(count)
from helpers import gcd SMALL_PRIMES = [2, 3, 5, 7, 11] SMALL_PRIMORDIAL = 1 for p in SMALL_PRIMES: SMALL_PRIMORDIAL *= p CANDIDATE_RESIDUES = [] for r in range(SMALL_PRIMORDIAL): if gcd(SMALL_PRIMORDIAL, r) == 1: CANDIDATE_RESIDUES.append(r) def candidate_prime_generator(): for p in SMALL_PRIMES: yield p k = 0 while True: for r in CANDIDATE_RESIDUES: if k > 0 or r > 1: yield SMALL_PRIMORDIAL * k + r k += 1 def factor(n): if n <= 0: raise ValueError output = ''
def QS(n, B, I): #single polynomial version of quadratic sieve, given smoothness bound B and sieve interval I global N global root global T #tolerance factor N, root, K, T = n, int(sqrt(n)), 0, 1 if is_probable_prime(N): return "prime" if isinstance(sqrt(N), int): return helpers.isqrt(N) #print(root) print("Attempting to factor {}...".format(N)) #F,I = size_bound(N) print("Generating {}-smooth factor base...".format(B)) factor_base = find_base(N, B) #generates a B-smooth factor base #print(factor_base) global F F = len(factor_base) print("Looking for {} {}-smooth relations...".format(F + T, B)) smooth_nums, xlist, indices = find_smooth(factor_base, N, I) #finds B-smooth relations, using sieving and Tonelli-Shanks print("Found {} B-smooth numbers.".format(len(smooth_nums))) print(smooth_nums) if len(smooth_nums) < len(factor_base): return ( "Not enough smooth numbers. Increase the sieve interval or size of the factor base." ) print("Building exponent matrix...") is_square, t_matrix = build_matrix(smooth_nums, factor_base) #builds exponent matrix mod 2 from relations if is_square == True: x = smooth_nums.index(t_matrix) factor = helpers.gcd(xlist[x] + sqrt(t_matrix), N) print("Found a square!") return factor, N / factor print("Performing Gaussian Elimination...") sol_rows, marks, M = gauss_elim( t_matrix) #solves the matrix for the null space, finds perfect square solution_vec = solve_row(sol_rows, M, marks, 0) '''vec = [0]*len(smooth_nums) # prints solution vector for i in solution_vec: vec[i] = 1 print("Solution vector found: " + str(vec))''' print("Solving congruence of squares...") #print(solution_vec) factor = solve(solution_vec, smooth_nums, xlist, N) #solves the congruence of squares to obtain factors for K in range(1, len(sol_rows)): if (factor == 1 or factor == N): print("Didn't work. Trying different solution vector...") solution_vec = solve_row(sol_rows, M, marks, K) factor = solve(solution_vec, smooth_nums, xlist, N) else: print("Found factors!") return factor, int(N / factor) return ("Didn't find any nontrivial factors!")
from helpers import gcd from helpers import sieve primes = sieve(100000) #answer is the first number n such that ord_{9n}(10) is >1000000 def o(n): answer = 1 while (pow(10, answer, 9 * n) != 1): answer += 1 return (answer) done = False count = 3 answer_count = 0 print(o(91)) l = [] while (not done): if (gcd(10, count) == 1 and count % o(count) == 1 and count not in primes): print('answer #%s = %s' % (answer_count + 1, count)) answer_count += 1 l.append(count) if (answer_count == 25): print('done') break count += 1 print('final answer:', sum(l))
a = k * (m**2 - n**2) b = 2 * k * m * n if (a > 2 * lim or b > 2 * lim): return (0) return (f(a, b)) print(get_num_of_cuboids(10, 1, 1)) print(get_num_of_cuboids(2, 1, 26)) m = 2 n = 1 count = 0 while (m < 500): while (n < m): if (gcd(m, n) == 1): #if(get_num_of_cuboids(m,n,1) > 0): #print(m,n) k = 1 while (get_num_of_cuboids(m, n, k) > 0): #print('get_num_of_cuboids(%s,%s,%s)=%s'%(m,n,k,get_num_of_cuboids(m,n,k))) count += get_num_of_cuboids(m, n, k) k += 1 n += 2 m += 1 if (m % 2 == 0): n = 1 else: n = 2
def is_terminating_expression(x, modulus): return gcd(x, modulus) > 1