Exemplo n.º 1
0
def cc(coins,args):
	#Calculate the difference between Ceiling and Formula values

	f = open("dump.txt","w")	

	start = int(args[0])
	uniquePolys = int(lcm(coins))

	for i in range(start,start+uniquePolys):
		
		#Same as AP, Passing Arguments into LC
		passArg = [str(i),str(uniquePolys),"4"]

		equation = lc(coins,passArg).split("\n")[0]
#		f.write(equation +" ")
		equation = equation.split()
		
		#Value when start is plugged in, using Ceiling
		result = 0
		for i in range(0,len(equation)-1):
			coef = float(equation[i].split("x^")[0])
			degree = int(equation[i].split("x^")[1])
			result+=coef*start**degree
			
		f.write(str(ceil(result)) + " ")

		#Add the constant term
		result+=float(equation[-1].split("x^")[0])
		result = round(result,PRECISION)
		
		f.write(str(result))
		f.write("\n")

	f.close()
Exemplo n.º 2
0
 def play(self):
     fullTime = util.lcm(self.government_period, self.public_period)
     self.government_strategy = self.getStrategyForAllPeriod(self.government_strategy, self.government_period,
                                                             fullTime)
     self.public_strategy = self.getStrategyForAllPeriod(self.public_strategy, self.public_period, fullTime)
     self.payoff = [0, 0]
     for x in range(0, fullTime):
         self.payoff = util.add(self.getPayoff(x), self.payoff)
     return self.payoff
Exemplo n.º 3
0
def part2(moons):
    orig = moons.copy()
    x, y, z = False, False, False
    for i in range(1, steps + 1):
        moons = time_step(moons)
        if not x and originals('x', orig, moons):
            print(f'all xs are back to original at step {i}')
            x_cycle = i
            x = True
        if not y and originals('y', orig, moons):
            print(f'all ys are back to original at step {i}')
            y_cycle = i
            y = True
        if not z and originals('z', orig, moons):
            print(f'all zs are back to original at step {i}')
            z_cycle = i
            z = True
        if x and y and z:
            ans = lcm(x_cycle, lcm(y_cycle, z_cycle))
            # part 2 374307970285176
            print(f'part 2: {ans}')
            break
Exemplo n.º 4
0
    def get_range(self):
        """Get a high and low value for this restriction.

        This pulls the highest argument of a min restriction and the lowest
        argument of a max restriction and the LCM of a mod restriction.

        Returns
        -------
        range : tuple(min, max, step)
        """
        min_value = None
        max_value = None
        step = None
        for validator in self.validators:
            func_name = validator[0].__name__
            if func_name == 'deferred_validate':
                func_name = validator[1].__name__
                if 0 in validator[2]:
                    arg = validator[3]()
                else:
                    arg = validator[3]
            else:
                arg = validator[1]
            if 'min' in func_name:
                if min_value is None:
                    min_value = arg
                else:
                    min_value = max(min_value, arg)
            elif 'max' in func_name:
                if max_value is None:
                    max_value = arg
                else:
                    max_value = min(max_value, arg)
            elif 'mod' in func_name:
                if step is None:
                    step = arg
                else:
                    step = lcm(step, arg)
        if min_value and step:
            for i in xrange(step):
                if not (min_value+i) % step:
                    min_value = min_value+i
                    break
        if max_value and step:
            for i in xrange(0, -step, -1):
                if not (max_value+i) % step:
                    max_value = max_value+i
                    break
        return (min_value, max_value, step)
Exemplo n.º 5
0
def sm_note_data(notes, columns):
	if len(notes) == 0: return "" # Some Malody charts are weird
	
	# key = measure number, value = list of notes
	bars = {}
	for note in notes:
		if note.row.bar in bars:
			bars[note.row.bar].append(note)
		else:
			bars[note.row.bar] = [note]
	
	bar_texts = []
	for i in range(max(bars) + 1):
		bar_notes = bars.get(i, None)
		if bar_notes is None:
			# The following generates e.g. for 6k
			# "000000\n000000\n000000\n000000"
			bar_texts.append("\n".join(["0" * columns] * 4))
			continue
		
		snaps = [note.row.snap for note in bar_notes]
		beats = [note.row.beat for note in bar_notes]
		snap = lcm(snaps)
		snap = snap // gcd([snap, *beats]) # Snap is unneccesarily big sometimes
		snap = min(192, snap) # Limit snap to 192nds
		
		rows = [[0] * columns for _ in range(snap)]
		
		for note in bar_notes:
			row_pos = round(note.row.beat / note.row.snap * snap)
			
			# Sometimes we have, say, a beat on 383 when the snap is 384
			# Snapping to 192nds makes that beat become 191.5, which is
			# rounded to 192 and boom, we have an out-of-bounds beat.
			# So we clamp this to snap-1 (191 in this example) to avoid
			row_pos = min(row_pos, snap - 1)
			
			try:
				rows[row_pos][note.column] = note.note_type.to_sm()
			except Exception as e:
				print(row_pos, note.column)
				print("Columns", columns, "Snap", snap)
				raise e
		
		bar_texts.append("\n".join("".join(map(str, row)) for row in rows))
	
	return "\n,\n".join(bar_texts)
Exemplo n.º 6
0
def ap(coins,args):

	f = open("dump.txt","w")
	
	start = int(args[0])
	iterations = len(coins)
	uniquePolys = int(lcm(coins))
	
	for i in range(start,start+uniquePolys*iterations):
		
		#Argument to Pass Into the LC Function (Starting Value,Step, Number of Iterations)
		passArg = [str(i),str(uniquePolys),str(iterations)]

		#Write the current number (Loops mod Polys because they all should be the same)
		#Also write the actual polynomial

		f.write(str(i%uniquePolys) + " "+lc(coins,passArg).split("\n")[0] + "\n")	
	f.close()
Exemplo n.º 7
0
    def generate_keys(self, bit_length=1024, e=65537):

        p = number.getPrime(bit_length)
        q = number.getPrime(bit_length)
        n = p * q
        # Carmichael's totient function, which is the same as Euler's in this case.
        l = lcm(p - 1, q - 1)
        d = self.inverse(e, l)

        if self.gmp:
            from gmpy2 import mpz
            public_key = (mpz(n), mpz(e))
            private_key = (mpz(n), mpz(d))
            return (mpz(p), mpz(q), mpz(n), mpz(l), mpz(e), mpz(d), public_key,
                    private_key)

        else:
            public_key = (n, e)
            private_key = (n, d)
            return (p, q, n, l, e, d, public_key, private_key)
Exemplo n.º 8
0
def select_basis(b) :        # b is numpy array
    (j,k) = b.shape          # j = k+1
    global Z
    if Z is None :
        Z = np.zeros(k)      # TODO : cek apakah rekursif berpengaruh
    b[0] =  map(lambda x: round(x,14), b[0])  # cek pembulatan nol pd b0
    if all( b[0]==Z ) :
        if len(b) > 1 :
            basis = b[1:]
        else :
            basis = []
    else :
        # tes apakah b[0]= kombinasi linear dari b[1]..b[j-1]
        # menggunakan eliminasi Gauss
        c = solve_linear( (b[1:j].astype(float)).T , [ b[0] ] ) 
        
        a = np.empty([j-1,k], dtype=object)
        if c==[] :                      # b[0] bebas linear thd b lain
            a[0] = np.copy(b[0])
        else :
            xs = c.T[0]                 # c msh dalam represnt kolom
            # khusus bagian ini lihat buku Bremner p.185
            # kita tidak perlu y dan z karena sdh ditangani oleh Fraction
            # tidak perlu menangani x_i = 0
            i = findNZ1( xs )
            f = Fraction( str(xs[i]) )
            m = f.denominator
            i2 = i+1
            while i2 <  len(xs) :
                if xs[i2] :
                    f = Fraction( str(xs[i2]) )
                    m = lcm( f.denominator, m )
                i2 += 1
                
            d = long( round( m*xs[i] ) )
            i += 1
            while i <  len(xs) :
                if xs[i] :
                    x = long( round(m*xs[i]) )
                    d = gcd( x,d )
                i += 1
            
            # python perlu denominator tetap positif
            if d < 0 :
                m *= -1
                d *= -1
            # f adalah bentuk rasional m/d yg jika relative prima = p/q
            # yg berarti faktor bersama nya dikeluarkan dan diambil q nya
            f = Fraction( '%d/%d' % (m,d) )
            if m < 0 :
                a[0] = ( -1.0/f.denominator )*b[0]
            else :
                a[0] = ( 1.0/f.denominator )*b[0]

        # proyeksi b ke a[0]. karena b[0] sdh diproses, maka
        # b yg diproyeksi berikutnya adalah 1,2..j-1
        b_ = orthoproject( a[0], b[1:] )
        # rekursif
        v = select_basis(b_)        
        # hasil dari rekursif digunakan utk lifting dari c ke a
        i = 1                     # a[0] sudah diproses
        for c in v :
            a[i] = lifting(b, c)
            i += 1
        
        basis = a
        
    return basis
Exemplo n.º 9
0
import util

n = 1
for i in range(1, 21):
  n = util.lcm(i, n)
print n
Exemplo n.º 10
0
 def union(self, other_set):
     new_hash = lcm(self.hash, other_set.hash)
     new_set = GodelHashSet()
     new_set.hash = new_hash
     return new_set
Exemplo n.º 11
0
def main():
    l = lcm(20,19)
    for i in range(18,0,-1):
        l = lcm(l,i)
    print l
Exemplo n.º 12
0
    def split(self, items, actors, costs, exclusive=True):
        print "Attempting to split:"
        print "== Items: "
        pprint(items)
        print "== between:"
        pprint(actors)
        print "== as per the costs:"
        pprint(costs)
        print "== Expanding the actors and items =="

        def expand_list(lst, new_length):
            # This ensures that if we have more items than actors or more actors
            # than items, we ensure that we always return the optimal result
            expanded_lst = lst * (new_length / len(lst))
            return [item + "-" + str(index / len(lst)) for index, item in enumerate(expanded_lst)]

        lcm_actors_items = lcm(len(actors), len(items))
        expanded_actors = expand_list(actors, lcm_actors_items)
        expanded_items = expand_list(items, lcm_actors_items)

        cost_dict = {}
        for cost in costs:
            cost_dict[(cost.item, cost.actor)] = cost

        exp_cost = {}
        for actor in expanded_actors:
            for item in expanded_items:
                root_actor = actor[: actor.rfind("-")]
                root_item = item[: item.rfind("-")]
                real_item = item[item.find("-") + 1 :] == "0"
                if real_item:
                    original_cost = cost_dict[(root_item, root_actor)]
                    exp_cost[(item, actor)] = Cost(item, actor, original_cost.amount)
                else:
                    exp_cost[(item, actor)] = Cost(item, actor, 0)

        cost_dict = exp_cost
        new_costs = [Cost(b.item, b.actor, b.amount) for k, b in cost_dict.iteritems()]
        averages = self.calc_averages(expanded_items, new_costs)

        edges = []
        for i in range(len(expanded_items)):
            for j in range(len(expanded_actors)):
                if (expanded_items[i], expanded_actors[j]) in cost_dict:
                    cost = cost_dict[(expanded_items[i], expanded_actors[j])]
                    edges.append((i, len(expanded_items) + j, self.score(cost, averages)))

        # Actually do the auction, maximizing whatever score function we have
        mw = mwmatching.maxWeightMatching(edges, maxcardinality=True)
        result = {}
        for i in range(len(expanded_items)):
            if mw[i] != -1:
                winner = expanded_actors[mw[i] - len(expanded_items)]
                result[expanded_items[i]] = (winner, cost_dict[(expanded_items[i], winner)].amount)
            else:
                result[expanded_items[i]] = None

        final_result = {}
        for item, winner in result.iteritems():
            root_item = item[: item.rfind("-")]
            root_winner = (winner[0][: winner[0].rfind("-")], winner[1])
            real_item = item[item.find("-") + 1 :] == "0"
            if real_item:
                final_result[root_item] = root_winner

        return final_result