def mdc_reduce(machine): stack = [machine] while stack: m = stack.pop() if m.is_trivial(): return True m = m.md_reduce() fs = factor.factor(m) if not fs: m = m.dual() if m.is_trivial(): return True fs = factor.factor(m) if not fs: continue for a, b in fs: c = mealy.product(b, a) d = c.md_reduce() if d.is_trivial() or d.dual().is_trivial(): return True if d != c and d.dual() != c: stack.append(d) return False
def smallest_multiple(divisors): """ Returns the smallest positive integer evenly divisible by all of the integers in divisors. """ # Maps each prime factor to a count (e.g. 8 factors into three 2s, so its # map would look like {2 : 3}). factor_counts = defaultdict(int) # Factor all integers in the list of divisors. for d in divisors: t = tree.Tree(d) f.factor(t) # Count up the num of occurrences of each prime factor. leaf_counts = defaultdict(int) # defaultdict sets initial counts to 0 for leaf in t.get_leaves(): leaf_counts[leaf] += 1 # If num of occurrences of a factor exceeds what we already have, # change count to the larger value (e.g. a number needs at least three # 2s in its list of prime factors in order to be divisible by 8). for leaf in leaf_counts: if (factor_counts[leaf] < leaf_counts[leaf]): factor_counts[leaf] = leaf_counts[leaf] # Now that we have a count of all prime factors for our smallest multiple, # we multiply them all together. smallest_multiple = 1 for factor in factor_counts: smallest_multiple *= factor ** factor_counts[factor] return smallest_multiple
def is_primitive(x, p): for q in factor(p - 1): if len(factor(q)) == 0: v = (x**((p - 1) / q) % p) # print('testing {}**(({} - 1)/{}) % {} = {}'.format(x, p, q, p, v)) if v == 1: return False return True
def largest_prime_factor(n): """ Generates a factor tree then performs depth-first search to find largest prime factor. """ t = tree.Tree(n) factor.factor(t) largest = dfs(t) return largest
def _evaluate_one(self, n, num_p): start_init_time = time() pqs = PQSieve(n, h=[], num_p=num_p, progress=False ) end_init_time = time() start_search_time = time() res = pqs.search() end_search_time = time() self.init_times.append(end_init_time - start_init_time) self.search_times.append(end_search_time - start_search_time) self.res_list.append(res) self.primes_used_list.append(pqs.primes_used) self.R_size_list.append(pqs.R_size) self.total_i_list.append(pqs.total_i) self.last_j_list.append(pqs.last_j) self.last_r_list.append(pqs.p_plus_q) self.T_list.append(pqs.p_plus_q - pqs.sqrt_n + 1) Tp = pqs.last_j - pqs.b0_ind + 1 if pqs.total_i == 0 else (pqs.R_size - pqs.b0_ind) + (pqs.total_i - 1) * pqs.R_size + (pqs.last_j + 1) self.Tp_list.append(Tp) del pqs start_qs_time = time() qs_res = qs.factor(n) end_qs_time = time() self.qs_times.append(end_qs_time - start_qs_time) self.qs_res_list.append(qs_res)
def _evaluate_fermat(self, n): start_init_time = time() fermat = Fermat(n, progress=False) end_init_time = time() start_search_time = time() res = fermat.search() end_search_time = time() self.init_times.append(end_init_time - start_init_time) self.search_times.append(end_search_time - start_search_time) self.res_list.append(res) self.primes_used_list.append([]) self.R_size_list.append(0) self.total_i_list.append(fermat.total_i) self.last_j_list.append(0) self.last_r_list.append(fermat.p_plus_q) self.T_list.append(fermat.p_plus_q - fermat.sqrt_n + 1) Tp = fermat.total_i + 1 self.Tp_list.append(Tp) del fermat start_qs_time = time() qs_res = qs.factor(n) end_qs_time = time() self.qs_times.append(end_qs_time - start_qs_time) self.qs_res_list.append(qs_res)
def minG(m): p = phi(m) mp = factor(p) checkLst = [p // i for i in mp] i = 2 while 1: if all((i**n - 1) % m != 0 for n in checkLst): return i i += 1
def gs(m, num=100): '''return list of m's primary roots below num''' p = phi(m) mp = factor(p) checkLst = [p // i for i in mp] return [ i for i in range(2, num) if all((i**n - 1) % m != 0 for n in checkLst) ]
def test_factor(self): for k in range(5): for _ in range(500): expected = sorted(random.choices(PRIMES, k=k)) N = product(expected) with self.subTest(N=N, expected=expected): found = sorted(factor(N)) self.assertEqual(expected, found)
def is_prim_root(x: int, modulus: int) -> bool: phi_modulus = phi.phi(modulus) phi_factor_dict = factor.factor(phi_modulus) for single_factor in phi_factor_dict.keys(): if (modular_exp.modular_exp(x, phi_modulus // single_factor, \ modulus) == 1): return False return True
def print_solution(ret): # print solution out = [] prod = 1 for x,y in zip(P, ret): if y: out.append(x) prod *= x print N, prod, prod%N, out print tm(out),"%",tm(factor(N)[0]),"==",prod%N
def addtl_augs(strength, img_in, lbl_in, i=0): print('\nCreate additional variation {0}'.format(str(i + 1))) addtl_choices = { 0: img_in, 1: HighContrast, 2: LowContrast, 3: Sharpen, 4: Blur, 5: UniformNoise, 6: TV_Chambolle, 7: HistogramEqualization, 8: [img_in, Skew], 9: [HighContrast, Skew], 10: [LowContrast, Skew], 11: [Sharpen, Skew], 12: [Blur, ElasticDistortion], 13: [UniformNoise, ElasticDistortion], 14: [TV_Chambolle, ElasticDistortion], 15: [HistogramEqualization, ElasticDistortion] } if factor(strength, i) == 0: img_out, lbl_out = img_in, lbl_in else: if i == 0: img_out, lbl_out = img_in, lbl_in elif i < 8: img_out, lbl_out = addtl_choices[i](img_in, factor(strength, i)), lbl_in else: if i == 8: img1 = img_in else: img1 = addtl_choices[i][0](img_in, factor(strength, i - 8)) if i < 12: img_out, lbl_out = addtl_choices[i][1](img1, lbl_in, factor(strength, 8)) else: img_out, lbl_out = addtl_choices[i][1](img1, lbl_in, factor(strength, 9)) return img_out, lbl_out, addtl_choices
def phi(n: int) -> int: if (n == 1): return 1 factor_dict = factor.factor(n) result = functools.reduce(operator.mul, map(lambda x: n - n // x, factor_dict.keys())) result = result // exp.exp(n, len(factor_dict.keys()) - 1) return result
def create_key(): """ return (pub_key, priv_key) pair """ while True: p = get_rand_prime(2**10, 2**16) q = get_rand_prime(2**10, 2**16) if gcd(p, q) == 2: break phi = (p - 1) * (q - 1) f = factor(p - 1) + factor(q - 1) d, dp, dq = 0, 0, 0 while True: e = get_rand_prime(1, phi) if e not in f: d = eea(e, phi)[1] dp = d % (p - 1) dq = d % (q - 1) if dp & 1 == dq & 1: break return (e, p * q), (p, q, dp, dq)
def experiment(k, lamb): print(f"Process {k} {lamb} start") folder = f"./record/k_{k}_lambda_{lamb}" if not os.path.exists(folder): os.makedirs(folder) with open(os.path.join(folder, "log.txt"), 'w+') as f: Xtrain = np.array(load_npz("train.npz").todense()) Xtest = np.array(load_npz("test.npz").todense()) U, V, record = factor(Xtrain, Xtest, k, 1e-2, lamb, 500, rmse_thd=1e-5, f=f) np.savetxt(os.path.join(folder, "U.txt"), U) np.savetxt(os.path.join(folder, "V.txt"), V) with open(os.path.join(folder, "record.json"), "w") as f: record = [(float(x[0]), float(x[1])) for x in record] f.write(json.dumps(record)) print(f"process k: {k}, lambda {lamb} finish")
def get_prim_root_generic(n: int) -> int: stats = get_prim_root_stats(n) p = stats[2] l = stats[3] if (stats[0] == False): raise ValueError("get_prim_root_generic: no primitive " + \ "root of %d" % n) # 若 p == 2,则一定 n == 2 或 n == 4 if (p == 2): # n == 4 if stats[1]: return 3 # n == 2 else: return 1 if stats[1]: modulus = n // 2 else: modulus = n phi_modulus = phi.phi_prime_power(p, l) phi_factor_dict = factor.factor(p - 1) # 不存在的因数不应该加入字典 if (l != 1): phi_factor_dict[p] = l - 1 for i in range(2, n): failed_flag = False for single_factor in phi_factor_dict.keys(): if (modular_exp.modular_exp(i, \ phi_modulus // single_factor, modulus) == 1): failed_flag = True break if (failed_flag): continue else: return i # 不应该运行到这里 raise RuntimeError("get_prim_root_generic: cannot find " + \ "primitive root of %d while it must have one" % n)
def get_prim_root_list(n: int) -> int: stats = get_prim_root_stats(n) p = stats[2] l = stats[3] if (stats[0] == False): raise ValueError("get_prim_root_generic: no primitive " + \ "root of %d" % n) # 若 p == 2,则一定 n == 2 或 n == 4 if (p == 2): # n == 4 if stats[1]: return 3 # n == 2 else: return 1 result = [] modulus = exp.exp(p, l) phi_modulus = phi.phi_prime_power(p, l) phi_factor_dict = factor.factor(p - 1) # 不存在的因数不应该加入字典 if (l != 1): phi_factor_dict[p] = l - 1 for i in range(2, p): failed_flag = False for single_factor in phi_factor_dict.keys(): if (modular_exp.modular_exp(i, \ phi_modulus // single_factor, modulus) == 1): failed_flag = True break if (failed_flag): continue else: result.append(i) return result
#!/usr/bin/python import itertools import factor dlimit = 20 if dlimit < 3: dlimit else: common_factors = {} for x in range(3, dlimit): factors = factor.factor(x) mcf = [] for k, g in itertools.groupby(sorted(factors)): z = list(g) mcf = z if len(z) > len(mcf) else mcf if mcf[0] not in common_factors or len(mcf) > common_factors[mcf[0]]: common_factors[mcf[0]] = len(mcf) prod = 1 print(common_factors) for x in common_factors: prod *= x ** common_factors[x] print(prod)
def generator(x): fact, phi = factor(x-1) #g = sorted(fact)[::-1][0] return fact
def factorUnary(inString): M = len(inString) return factor(str(M))
def factsuff(): if tk.token.code == CodeTable['*'] or tk.token.code == CodeTable['/']: muloper() factor() factsuff()
def test_factor_7_return_7_in_list(self): self.assertEqual(factor.factor(7), [7])
#!/usr/bin/python #acleetus from factor import factor from triangle import triangle from doubling import doubling from factorial import factorial from pascal import pascal from occurrences import num_occurrences print factor(60) print factor(45) print factor(35) print factor(13) triangle(3) triangle(5) print doubling(0.1) print doubling(0.05) print doubling(0.01) print factorial(4) print factorial(0) pascal(10) print num_occurrences(["a", "b", "a", "b", "c", "b", "d", "e"], "b")
def test_factor_9_return_3_3_in_list(self): self.assertEqual(factor.factor(9), [3, 3])
def get_expts(nrange): nums = factor(this_num) return [nums.get(n, 0) for n in nrange]
def test_factor_one_return_empty_list(self): self.assertEqual(factor.factor(1), [])
def test_factor_zero_return_empty_list(self): self.assertEqual(factor.factor(0), [])
def test_factor_big_return_correct_in_list(self): self.assertEqual(factor.factor(2 * 2 * 3 * 5 * 5 * 7 * 11 * 17 * 19), [2, 2, 3, 5, 5, 7, 11, 17, 19])
#problem3.py import sys, math sys.path.append('/Users/nathanielgentile/Documents/OCW/compsci101/Python') import factor factlist = [] for i in range(1, int(math.sqrt(600851475143))+1): if factor.factor(i, 600851475143): factlist.append(i) print factlist
def test_factor_8_return_2_2_2_in_list(self): self.assertEqual(factor.factor(8), [2, 2, 2])
#!/usr/bin/python3 from factor import factor from collections import Counter n = 10000 factors_last = factor(n) while True: n += 1 factors_n = factors_last factors_n1 = factor(n+1) factors_last = factors_n1 factors_triangular = Counter(factors_n) #+ factors_n1 factors_triangular += Counter(factors_n1) factors_triangular[2] -= 1 # simulate dividing by 2 # Get the factor exponents exp = factors_triangular.values() num_divisors = 1 for i in exp: num_divisors *= int(i)+1 if num_divisors >= 500: triangular = (n+1)*n/2 print(triangular) print(factors_triangular) break
def primitives_of(m): assert len(factor(m)) == 0 for i in range(1, m): if is_primitive(i, m): print(i)
def test_factor_big2_return_correct_in_list(self): self.assertEqual(factor.factor(5993), [13, 461])
def match(self,patname,srcname): """ given a pattern image and a source image, return the match result and the scaling factor """ p = Image.open(patname).convert('L') pa = numpy.array(p) pa *= 255.0/pa.max() s = Image.open(srcname).convert('L') sa = numpy.array(s) sa *= 255.0/sa.max() pre = process.process() ex= findextrema.findextrema() des = descriptor.descriptor() scale = factor.factor() pdata = pre.creatdog(pa) sdata = pre.creatdog(sa) pDes = [] sDes = [] # dict to store all the feature matching result result = {} pFeatures = ex.get_Patextremes(pdata,pa) sFeatures = ex.get_Srcextremes(sdata,sa) # assign decriptors for each feature points pDes = des.creatDes(pFeatures,pa) sDes = des.creatDes(sFeatures,sa) tree = [] if sDes=={} or pDes=={}: return False else: # use cKD tree struture to compute the two similar pixels tree = scipy.spatial.cKDTree(sDes.values()) slocList = sDes.keys() pDict = {} sDict = {} for p in pDes.keys(): x = pDes[p] re = tree.query(x,k=2,eps=self.distanceThresh,p=2, distance_upper_bound=numpy.inf) if re[0][1]!=0 and re[0][0]/re[0][1] < self.similarityThresh: pLoc = p sLoc = slocList[re[1][0]] distance = re[0][0] # did not been compared before if sDict.has_key(sLoc)==False: # add the result and compared pattern pixel # and source pixel result[(pLoc,sLoc)] = distance pDict[pLoc] = sLoc sDict[sLoc] = pLoc elif distance < result.get((sDict[sLoc],sLoc)): # updates the result and compared pattern pixel # and source pixel del result[(sDict[sLoc],sLoc)] result[(pLoc,sLoc)] = distance del pDict[sDict[sLoc]] pDict[pLoc] = sLoc sDict[sLoc] = pLoc elif re[0][1]==0: pLoc = p sLoc = slocList[re[1][0]] distance = re[0][0] # did not been compared before if sDict.has_key(sLoc)==False: # add the result and compared pattern pixel # and source pixel result[(pLoc,sLoc)] = distance pDict[pLoc] = sLoc sDict[sLoc] = pLoc elif distance < result.get((sDict[sLoc],sLoc)): # updates the result and compared pattern pixel # and source pixel del result[(sDict[sLoc],sLoc)] result[(pLoc,sLoc)] = distance del pDict[sDict[sLoc]] pDict[pLoc] = sLoc sDict[sLoc] = pLoc # the list of matched pixels, sorted by the distance finResult = sorted(result.items(), reverse=False, key=lambda d: d[1]) match1 = finResult[0][0] match2 = finResult[1][0] match3 = finResult[2][0] scalingFactor = scale.cal_factor(match1,match2,match3) return finResult,scalingFactor
# instasolve #P = primes[20:47] #N = reduce(lambda x,y: x*y, primes[0:9]) #P = primes[20:90] #N = reduce(lambda x,y: x*y, primes[0:4]) # testing P = primes[20:56] N = reduce(lambda x,y: x*y, primes[0:11]) #print P print "2^%d" % len(P) print "finding", N ret, phi = factor(N) print phi ret = sorted(list(set(ret))) print ret #exit(0) odds = log(phi)/log(2) print "2^%f" % odds print "will find",len(P)-odds if len(P)-odds < 1.0: exit(-1) pass """
#!/usr/bin/python3 import numpy as np from collections import defaultdict from factor import factor lcm_factors = defaultdict(int) N=20 for i in range(2,N+1): f = factor(i) for k,v in f.items(): lcm_factors[k] = max(lcm_factors[k], v) n = 1 for k,v in lcm_factors.items(): print(k) print(v) n *= k**v print(n) print(lcm_factors) print(n)
##problem 5.py import sys, math sys.path.append('/Users/nathanielgentile/Documents/OCW/compsci101/Python') import factor t = True init = 24504480 while t: init += 1 for i in range(20, 0, -1): if i == 1: t = False elif factor.factor(i, init): continue else: break print init #takes a while
def factor_to_string(num): facs = factor(num) facs = ["{}**{}".format(n, p) for n, p in sorted(facs.items(), key=lambda n: n[0])] return ' * '.join(facs)
def pow_orders(d, n): fs = [1, d] + factor(d) for x in range(1, n): if order(x, n) in fs: print(x)
def spike(A, b, config, output = True, debug = False) : # Check the values if (config['partitionNumber'] < 2) : raise ValueError("The partitionNumber has to be at least 2 but it is", config['partitionNumber']) elif (config['matrixSize'] / config['partitionNumber'] < config['bandwidth']) : raise ValueError("The number of partitions must be smaller or equal to", config['matrixSize'] / config['bandwidth'], "but it is", config['partitionNumber']) elif (config['matrixSize'] % config['partitionNumber'] != 0) : raise ValueError("The matrixSize should be devideable by the number of partitions. given:", config['matrixSize'], config['partitionNumber']) else : # Determine the size of each partition config['partitionSize'] = config['matrixSize'] / config['partitionNumber'] # make bandwidth even if (config['bandwidth'] % 2 != 0) : config['bandwidth'] += 1 config['rhsSize'] = b.shape[1] config['offdiagonalSize'] = config['bandwidth']/2 #(bandwidth-1)/2 if (output) : print config print "input A:" print A.todense() print "input b:" print b.todense() # create prerequirements for OpenCL ctx = cl.create_some_context(True) #for platform in cl.get_platforms() : # devices = platform.get_devices(cl.device_type.CPU) # ctx = cl.Context(devices) queue = cl.CommandQueue(ctx) # compile programm code for CL directory = os.path.dirname(os.path.realpath(__file__)) gaussFile = open(os.path.join(directory, "gauss.cl"), 'r') gaussCode = ''.join(gaussFile.readlines()) program = cl.Program(ctx, gaussCode).build() # 1. Pre-processing # 1.1 Partitioning of the original system onto different processors start = time() buffers = partition.partition(config, ctx, A, b, debug) # 1.2 Factorization of each diagonal block # solve A_j[V_j, W_j, G_j] = [(0 ... 0 B_j)T, (C_j 0 ... 0)T, F_j] # this step also involves solving of A_j G_j = F_j from (2.1) factor.factor(config, ctx, queue, program, buffers) # At this point we can free the A buffer (buffers[0]) # TODO make the memory release dependent on some event #buffers[0].release() # 2. Post-processing # 2.1 Solving the reduced system buffers = solve.reduced(config, ctx, queue, program, buffers, debug) # At this point we can free the SG buffer (buffers[2]) #buffers[2].release() # 2.2 Retrieving the overall solution x = solve.final(config, ctx, queue, program, buffers, debug) stop = time() rt = stop-start return [x, rt]