Esempio n. 1
0
File: PE_0540.py Progetto: mbh038/PE
def p540rm(N):
    
    t=time.clock()
    
    ctr=0
    
    for i in range(1,int((2*N/(1+(1+2**0.5)**2))**0.5)+1,2):
#        if i%2:
        n1=int(i//2**0.5+1)
        nv=int(((2*N-i*i)**0.5-i)//2)
#            print(n1,nv)
        for j in range(n1,nv+1):
            if math.gcd(i,j)==1:
                ctr+=1
    
    for i in range(1,int((N/(1+(1+2**0.5)**2))**0.5)+1):
        n1=int(i*2**0.5)+1
        nv=int((N-i*i)**0.5-i)
        for j in range(n1,nv+1):
            if j%2:
                if math.gcd(i,j)==1:
                    ctr+=1
     
    print(time.clock()-t)               
    print( ctr)
Esempio n. 2
0
def _brent(N):
    if N % 2 == 0:
        return 2
    y, c, m = random.randint(1, N - 1), random.randint(1, N - 1), random.randint(1, N - 1)
    g, r, q = 1, 1, 1
    while g == 1:
        x = y
        for i in range(r):
            y = ((y * y) % N + c) % N
        k = 0
        while k < r and g == 1:
            ys = y
            for i in range(min(m, r - k)):
                y = ((y * y) % N + c) % N
                q = q * (abs(x - y)) % N
            g = math.gcd(q, N)
            k = k + m
        r = r * 2
    if g == N:
        while True:
            ys = ((ys * ys) % N + c) % N
            g = math.gcd(abs(x - ys), N)
            if g > 1:
                break

    return g
Esempio n. 3
0
def use_math_gcd():
    global lengthsDict
    for m in range(2, size//2):
        for n in range(1, m):
            # m - num has to be odd
            if (m - n) % 2 == 1:
                msq = m * m
                nsq = n * n
                a = msq - nsq
                b = 2 * m * n
                c = msq + nsq
                length = a + b + c
                if length > size:
                    break
                if length <= size:
                    if math.gcd(a, b) == 1 and math.gcd(a, c) == 1 and math.gcd(b, c) == 1:
                        # if eu.primes.is_pythagorean_triple_primitive(a, b, c):
                        # print("Primitive ({},{},{}) --> {}".format(a,b,c,length))
                        mcount = 0
                        for mult in range(length, size + 1, length):
                            mcount += 1
                            # for each primitive and its multiples, add one to the possible ways of generating the length
                            if b > a:
                                # lengthsDict.setdefault(mult, []).append((a, b, c))
                                # primitives.add((a,b,c))
                                lengthsDict.setdefault(mult, []).append((mcount * a, mcount * b, mcount * c))
                            else:
                                # lengthsDict.setdefault(mult, []).append((b, a, c))
                                # primitives.add((b,a,c))
                                lengthsDict.setdefault(mult, []).append((mcount * b, mcount * a, mcount * c))
Esempio n. 4
0
def brent(n):
    g = 1
    while g == 1 or g == n:
        if n % 2 == 0:
            return 2
        y, c, m = random.randint(1, n - 1), random.randint(1, n - 1), random.randint(1, n - 1)
        g, r, q = 1, 1, 1
        while g == 1:
            x = y
            for i in range(r):
                y = ((y * y) % n + c) % n
            k = 0
            while k < r and g == 1:
                ys = y
                for i in range(min(m, r - k)):
                    y = ((y * y) % n + c) % n
                    q = q * (abs(x - y)) % n
                g = math.gcd(q, n)
                k += m
            r += r
        if g == n:
            while True:
                ys = ((ys * ys) % n + c) % n
                g = math.gcd(abs(x - ys), n)
                if g > 1:
                    break
    return g
Esempio n. 5
0
File: PE_0510.py Progetto: mbh038/PE
def p510(limit):
    t=time.clock()
    abc=[]
    for q in range(1,int(limit**0.5)+1):
        for p in range(1,q+1):
            if p*q%(p+q)==0:
                abc.append((p**2,q**2,(p*q//(p+q))**2))
    
#    abc=[(p**2,q**2,(p*q//(p+q))**2) for q in range(1,int(limit**0.5)+1) for p in range(1,q+1)if p*q%(p+q)==0]
    print(len(abc))
#    print(abc)
    print(time.clock()-t)
    abcfund=[]#set()
    for i in range(len(abc)):
        div=math.gcd(abc[i][0],math.gcd(abc[i][1],abc[i][2]))
        newTrio=(abc[i][0]//div,abc[i][1]//div,abc[i][2]//div)
        if newTrio not in abcfund:
            abcfund.append(newTrio)
    print("abcfund size: ",len(abcfund))
#    print(abcfund)
    print(time.clock()-t)
    S=0
    k=0
    for trio in abcfund:
        k+=1
        a,b,c=trio[0],trio[1],trio[2]
        L=limit//b
        S+=(a+b+c)*L*(L+1)//2
        if k%100==0:
            print(k,a,b,c,S,L)
    print(S)
    print(time.clock()-t)
Esempio n. 6
0
File: PE_0329.py Progetto: mbh038/PE
def p329hmmf(N=500,y=[0,0,0,0,1,1,0,0,0,1,0,0,1,0,1]):
    
    t0=time.clock()
    
    T=len(y) #length of sequence
    
    pinit=pif(N) #initial distribution
    A=tpmf(N) # transmission matrix
    B=epmf(N) # emission matrix
    
    alpha=np.zeros([T,N],dtype=object)
    
    # base case
    for i in range(N):
        alpha[0][i]=[B[y[0]][i][0]*pinit[i][0],B[y[0]][i][1]*pinit[i][1]]
    for i in range(1,T):
        for j in range(N):
            alpha[i][j]=[0,0]

    #step case
    for t in range(1,T):
        for i in range(N):
            s = [0,0]
            k=0
            while 1:
                if A[i][k][0]==0:
                    k+=1
                    continue
                else:
                    s[0] = A[i][k][0] * alpha[t-1][k][0]
                    s[1] = A[i][k][1] * alpha[t-1][k][1]
                    break
            for j in range(k+1,N):
                nnew=A[i][j][0] * alpha[t-1][j][0]
                if nnew==0:
                    continue
                dnew=A[i][j][1] * alpha[t-1][j][1]
                s[0]=s[0]*dnew+nnew*s[1]
                s[1]=s[1]*dnew
                gcd= math.gcd(s[0],s[1])
                s[0],s[1]=s[0]//gcd,s[1]//gcd
            alpha[t][i]=[0,0]    
            alpha[t][i][0] = B[y[t]][i][0] * s[0]
            alpha[t][i][1] = B[y[t]][i][1] * s[1]

    #final probability  
    s = [0,0];
    s[0]=alpha[T-1][0][0]
    s[1]=alpha[T-1][0][1]
    for i in range(1,N):
        nnew=alpha[T-1][i][0]
        if nnew==0:
            continue
        dnew=alpha[T-1][i][1]
        s[0]=s[0]*dnew+nnew*s[1]
        s[1]=s[1]*dnew
    gcd= math.gcd(s[0],s[1])
    
    print(str(s[0]//gcd)+'/'+str(s[1]//gcd))    
    print(time.clock()-t0)
Esempio n. 7
0
    def processor(iterator):
        for item in iterator:
            if item['fcontents']:
                tabdivisor = 0
                spacedivisor = 0
                for line in item['fcontents'].split('\n'):
                    tabs = 0
                    spaces = 0
                    for letter in line:
                        if letter == ' ':
                            spaces += 1
                        elif letter == '\t':
                            tabs += 1
                        else:
                            break
                    tabdivisor = gcd(tabdivisor, tabs)
                    spacedivisor = gcd(spacedivisor, spaces)
                    # click.echo('{} tabs {} spaces'.format(tabs, spaces))
                if spacedivisor > 0:
                    click.echo('{}: {} spaces'.format(item['filename'], spacedivisor))
                elif tabdivisor > 0:
                    click.echo('{}: {} tabs'.format(item['filename'], tabdivisor))


            yield item
Esempio n. 8
0
def _gcd_recursive(*args):
    """
    Get the greatest common denominator among any number of ints
    """
    if len(args) == 2:
        return gcd(*args)
    else:
        return gcd(args[0], _gcd_recursive(*args[1:]))
Esempio n. 9
0
def to_verilator_cpp(top, verilog_prefix, sim_time=0):
    template_path = os.path.dirname(os.path.abspath(__file__))
    env = Environment(loader=FileSystemLoader(template_path))
    env.globals['zip'] = zip

    if hasattr(top, 'verilator_dumpfile'):
        dumpfile = top.verilator_dumpfile
    else:
        dumpfile = None

    clks = top.verilator_new_clock
    rsts = top.verilator_new_reset

    if hasattr(top, 'verilator_reset_statements'):
        inits_list = top.verilator_reset_statements
        inits = collections.OrderedDict()
        for init in inits_list:
            if isinstance(init, vtypes.Subst):
                inits[init.left] = init.right
    else:
        inits = {}

    ios = top.get_ports()
    inputs = [io_var for io_var in ios.values()
              if isinstance(io_var, vtypes.Input) and
              (io_var not in clks) and (io_var not in rsts)]

    time_step = None

    for hperiod in clks.values():
        if time_step is None:
            time_step = hperiod
        else:
            time_step = gcd(time_step, hperiod)

    for period, positive in rsts.values():
        if time_step is None:
            time_step = period
        else:
            time_step = gcd(time_step, period)

    if time_step is None:
        time_step = 1

    template_dict = {
        'verilog_prefix': verilog_prefix,
        'sim_time': sim_time,
        'time_step': time_step,
        'dumpfile': dumpfile,
        'clks': clks,
        'rsts': rsts,
        'inits': inits,
        'inputs': inputs,
    }

    template = env.get_template('verilator_template.cpp')
    code = template.render(template_dict)
    return code
Esempio n. 10
0
def my_gcd(a, b):
    '''
    returns: str
    gcd for two given numbers
    '''
    if a == b or b == 0:
        return a
    elif a > b:
        return gcd(a-b, b)
    else:
        return gcd(b-a, a)
Esempio n. 11
0
def resolve():
    import math
    n = int(input())
    dat_a = list(map(int, input().split()))
    dat_a = list(dat_a)
    m = []
    l = [0] * n
    r = [0] * (n + 1)
    l[0] = 0
    r[n - 1] = 0
    for i in range(n):
        l[i + 1] = math.gcd(l[i], dat_a[i])
        r[n - i-1] = math.gcd(r[n-i], dat_a[i])
Esempio n. 12
0
File: An.py Progetto: vdhan/RSA
def gcd(*a):
    """Return the greatest common divisor for 2 or more numbers"""
    if len(a) < 2:
        raise TypeError('gcd() takes at least 2 arguments')

    for i in a:
        if not math.isfinite(i):
            raise TypeError('Parameter Error!')

    b = math.gcd(a[0], a[1])
    for i in range(2, len(a)):
        b = math.gcd(b, a[i])

    return b
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    import warnings
    warnings.warn('fractions.gcd() is deprecated. Use math.gcd() instead.',
                  DeprecationWarning, 2)
    if type(a) is int is type(b):
        if (b or a) < 0:
            return -math.gcd(a, b)
        return math.gcd(a, b)
    return _gcd(a, b)
def normalize(list):
    if len(list) < 2:
        return list
    g = list[0]
    for n in list[1:]:
        g = gcd(g, n)
    return [n // g for n in list]
    def __init__(self, build_data, **options):
        """

        :param build_data: either two numbers (will be numerator and
        denominator of the fraction) or three numbers, the first being then a
        coefficient to multiply both others by.
        """
        if len(build_data) == 3:
            build_data = (Number(build_data[0]) * Number(build_data[1]),
                          Number(build_data[0]) * Number(build_data[2]))
        elif len(build_data) != 2:
            raise ValueError('Need either 2, or 3 numbers to build this '
                             'question.')
        super().setup('minimal', **options)
        super().setup('numbers', nb=build_data, shuffle_nbs=False,
                      **options)
        # We must have nb1 < nb2 in order to build the DividedLineSegment:
        if self.nb1 > self.nb2:
            self.nb1, self.nb2 = self.nb2, self.nb1
        self.transduration = 8
        if self.nb2 >= 5:
            self.transduration += 2 * (self.nb2 - 5)
        fc = next(shared.dvipsnames_selection_source)[0]
        self.dividedlinesegment = DividedLineSegment(Point(0, 0, 'A'),
                                                     Point(10, 0, 'B'),
                                                     n=self.nb2, fill=self.nb1,
                                                     fillcolor=fc)
        self.dividedlinesegment.scale = Number('0.6')
        self.dividedlinesegment.baseline = '4pt'
        self.wording = _('Which fraction of the line segment represents '
                         'the colored part?')
        self.fraction = f = Fraction(self.nb1, self.nb2)
        if f.is_reducible():
            f1 = f.reduce()
            if isinstance(f1, Fraction) and f1.is_reducible():
                f2 = f1.reduce()
                lpcd = prime_factors(gcd(int(f.numerator), int(f.denominator)))
                if isinstance(f2, Fraction) and f2.is_reducible():
                    self.answer_wording = _('{} (or {}, or {}...)') \
                        .format(shared.machine.write_math_style2(f.printed),
                                shared.machine.write_math_style2(f1.printed),
                                shared.machine.write_math_style2(f2.printed))
                elif lpcd[0] != lpcd[1]:
                    f3 = f.reduced_by(lpcd[1])
                    self.answer_wording = _('{} (or {}, or {}, or {})') \
                        .format(shared.machine.write_math_style2(f.printed),
                                shared.machine.write_math_style2(f1.printed),
                                shared.machine.write_math_style2(f3.printed),
                                shared.machine.write_math_style2(f2.printed))
                else:
                    self.answer_wording = _('{} (or {}, or {})') \
                        .format(shared.machine.write_math_style2(f.printed),
                                shared.machine.write_math_style2(f1.printed),
                                shared.machine.write_math_style2(f2.printed))
            else:
                self.answer_wording = _('{} (or {})') \
                    .format(shared.machine.write_math_style2(f.printed),
                            shared.machine.write_math_style2(f1.printed))
        else:
            self.answer_wording = shared.machine.write_math_style2(f.printed)
def multiplicativeKeyCount(alphabetLength, keepList=True):
    """Given a length of some alphabet, calculate how many valid multiplicative cipher keys that alphabet can have.

    Args:
        alphabetLength - The length of the alphabet
        keepList - Whether or not to actually keep track of the list of keys

    Returns:
        A tuple of the key count and the array of key values.  The second value is None if keepList is False.

    """
    keyCount = 0
    keyList = []
    # Start at 2 because 1 and 0 are never valid keys
    for i in range(2, alphabetLength):
        # Inrease the key count if the gcd of the two numbers is one.
        if gcd(i, alphabetLength) == 1:
            keyCount += 1
            # Add to the list of keys if we're keeping track of that
            if keepList:
                keyList.append(i)

    if keepList:
        return keyCount, keyList
    else:
        return keyCount, None
Esempio n. 17
0
File: PE_0127.py Progetto: mbh038/PE
def p127(limit):
    
    t=time.clock()
    rads=rsieve(limit+1)
    count=0
    csum=0    
    for c in range(1,limit):
        crads=rads[:c+1]
        crad=crads[c,1]
        radpair=crads[crads[:,1]<c/crad]
        if not c%2:
            radpair=radpair[radpair[:,0]%2==1]
        if len(radpair)<2:
            continue
        for i in range(len(radpair)):
            a=radpair[i]
            b=c-a[0]
            if b<a[0]:
                break                    
            brad=rads[b,1]
            if a[1]*brad*crad>=c:
                continue
            if math.gcd(a[0],b)>1:
                continue
            if b not in radpair[:,0]:
                continue
            csum+=c
            count+=1
            print((a[0],b,c),(a[1],rads[b][1],rads[c][1]))
    print(count,csum)    
    print(time.clock()-t)
Esempio n. 18
0
 def calc_aspect_str(self, wd, ht):
     # calculate the aspect ratio given by width and height and make
     # string of the form "x:y"
     gcd = math.gcd(wd, ht)
     _wd, _ht = int(wd / gcd), int(ht / gcd)
     _as = str(_wd) + ':' + str(_ht)
     return _as
Esempio n. 19
0
def p71(tnum, min_d, max_d):
    global solutions
    thread_num = tnum
    min_denom = min_d
    max_denom = max_d
    less_than = 3/7
    solution = [1,3,0.3333333333333333]
    
    #print("Thread %d starting. Checking denominators between %d and %d" % (thread_num, min_denom, max_denom))
    
    for i in reversed(range(min_denom,max_denom+1)):
        #print("Checking denominator: %d" % i)
        j = 1
        too_large = False
        while j < i and not too_large:
            fract = j/i
            if fract < less_than and fract > solution[2]:
                solution = [j,i,fract]
            elif fract > less_than:
                too_large = True
            j += 1

    com_dom = gcd(solution[0],solution[1])
    #solutions[thread_num] = [int(solution[0]/com_dom), int(solution[2]/com_dom)]
    print("Thread %d - Solution: %d/%d = %s" % (thread_num,  int(solution[0]/com_dom),int(solution[1]/com_dom),'{0:.16f}'.format(solution[2])))
Esempio n. 20
0
File: PE_0329.py Progetto: mbh038/PE
def p329(squares=500,croakString='PPPPNNPPPNPPNPN'):
    
    t=time.clock()
    
    probs=0
    croakseq=[pn=='P' for pn in croakString] 
    croaks=len(croakseq)
    primes=primeSieve(squares)

    for start in range (1,squares+1):
        
        for seq in it.product([1,-1],repeat=croaks-1):
            positions=[start]+[0]*(croaks-1)
            for j in range(len(seq)):
                if positions[j]+seq[j]>squares:
                    positions[j+1]=squares-1
                elif positions[j]+seq[j]<1:
                    positions[j+1]=2
                else:
                    positions[j+1]=positions[j]+seq[j]        
            matches=sum([primes[positions[k]] == croakseq[k] for k in range(len(croakseq))])
            probs+=2**matches
            
    denom=squares*2**(len(croakseq)-1)*3**len(croakseq)
    gcd= math.gcd(probs,denom)
    
    print( str(probs//gcd)+"/"+str(denom//gcd))

    print(time.clock()-t)
Esempio n. 21
0
def modular_inverse(a, m):
    """
    Return the value x so that a*x = 1 (mod m) -- that is, so that a*x = k*m + 1 for some non-negative integer k.
    :param a: Value of a -- positive integer. This is the encoding key in the crypto-setting
    :param m: Value of m -- positive integer This is the length of the alphabet in the crypto-setting
    :return: Solution x -- positive integer.
    """

    def extended_gcd(_a, _b):
        """ Use the Extended Euclidean algorithm to calculate the "extended greatest common divisor".
        It takes as input two positive integers a and b, then calculates the following:
        1. The greatest common divisor (gcd) between a and b -- that is, the integer number g which is the largest
            integer for which a/g and b/g both are integers  (This can also be obtained using math.gcd)
        2. The integer x and y so that a*x + b*y = gcd(x, y)
        :param _a: Positive integer
        :param _b: Positive integer
        :return: Tuple (gcd, x, y)
        """
        previous_remainder, remainder = _a, _b
        current_x, previous_x, current_y, previous_y = 0, 1, 1, 0
        while remainder > 0:
            previous_remainder, (quotient, remainder) = remainder, divmod(previous_remainder, remainder)
            current_x, previous_x = previous_x - quotient * current_x, current_x
            current_y, previous_y = previous_y - quotient * current_y, current_y
        # The loop terminates with remainder == 0, x == b and y == -a. This is not what we want, and is because we have
        # walked it through one time "too many". Therefore, return the values of the previous round:
        return previous_remainder, previous_x, previous_y

    gcd_value, x, y = extended_gcd(a, m)
    if gcd_value != 1:
        print('No inverse. gcd (%d, %d) is %d. Decoding is not unique. Choose another key than %d'
              % (a, m, math.gcd(a, m), a))
    return x % m
Esempio n. 22
0
def how_many_blue(total):
    # total * (total - 1) == 2 * blue * (blue - 1)
    # 2 * blue ** 2 - 2 * blue - (total ** 2 - total) == 0
    # [-b +/- (b ^ 2 - 4ac)] / 2a
    # blue = [2 +/- (4 + 8(total ^ 2 - total)) ** 0.5] / 4
    delta = (4 + 8 * (total ** 2 - total)) ** 0.5
    blue = (2 + delta) / 4
    if blue % 1 == 0:
        blue = int(blue)
        gcd_0 = gcd(blue, total)
        gcd_1 = gcd(blue - 1, total - 1)
        top = blue // gcd_0 * (blue - 1) // gcd_1
        bottom = total // gcd_0 * (total - 1) // gcd_1
        if bottom == 2 * top:
            return blue
    return None
Esempio n. 23
0
def main():
    # any primitive right triangle can be generated by n^2 - m^2, 2 nm, n^2 + m^2
    # Proof that this construction works
    """
    (n^2 - m^2)^2 + (2nm)^2
    n^4 - 2n^2 m^2 + m^4 + 4n^2 m^2
    n^4 + 2n^2 m^2 + m^4
    (n^2 + m^2)^2
    """

    MAXL = 1500000

    c = Counter()
    m = 1

    while perim(m + 1, m) <= MAXL:
        n = m + 1

        while perim(n, m) <= MAXL:
            if (n + m) % 2 == 0 or gcd(n, m) != 1:
                n += 1
                continue

            d = 1

            while d * perim(n, m) <= MAXL:
                c[d * perim(n, m)] += 1
                d += 1

            n += 1

        m += 1

    print(sum(1 for x in c if c[x] == 1))
 def get_solution(self):
     m = 2
     n = 1
     sol = 0
     a = 0
     b = 0
     c = 0
     target = 1000
     not_found = True
     while not_found:
         a = m * m - n * n
         b = 2 * m * n
         c = m * m + n * n
         ssum = a + b + c
         if target % ssum == 0:
             p = target // ssum
             a *= p
             b *= p
             c *= p
             sol = a * b * c
             break
         if ssum > target:
             n += 1
             m = n + 1
         else:
             m += 2
         while math.gcd(m, n) != 1:
             m += 2
     return "The triple [{0}, {1}, {2}] sums to {3}. It's product is {4}".format(a, b, c, target, sol)
Esempio n. 25
0
    def connect_rings(name1, name2, executor):
        """Determine suitable divisor for inter-ring connections."""

        sett = project.settings

        row_size1 = sett.row(name1)
        row_size2 = sett.row(name2)
        if row_size1 == row_size2:
            # All the same size, divide into quarters
            gcd = 4
        else:
            gcd = math.gcd(row_size1, row_size2)

        log.debug('using gcd: %r', gcd)
        step1 = row_size1 // gcd
        step2 = row_size2 // gcd

        start_idx1 = sett.start_offset(name1)
        start_idx2 = sett.start_offset(name2)
        ssize = project.stack_size

        for stepidx in range(gcd):
            idx1 = ssize * (start_idx1 + stepidx * step1)
            idx2 = ssize * (start_idx2 + stepidx * step2)

            log.debug('Connecting rings step %i, connecting %i - %i', stepidx,  idx1, idx2)
            submit_task(executor, idx1, idx2)
 def get_solution(self):
     ps = [0] * 1001
     max_perimeter = 1000
     n = 1
     m = n + 1
     just_set_n = True
     while True:
         while math.gcd(m, n) != 1:
             m += 2
         a = m * m - n * n
         b = 2 * m * n
         c = m * m + n * n
         p = a + b + c
         if p > max_perimeter:
             if just_set_n:
                 break
             n += 1
             m = n + 1
             just_set_n = True
             continue
         ps[p] += 1
         mul_p = p + p
         while mul_p <= max_perimeter:
             ps[mul_p] += 1
             mul_p += p
         just_set_n = False
         m += 2
     most_hit = 0
     max_hits = 0
     for i in range(len(ps)):
         if ps[i] > max_hits:
             most_hit = i
             max_hits = ps[i]
     return 'The most-hit perimeter for p <= {} was {}'.format(max_perimeter, most_hit)
Esempio n. 27
0
def roots_cyclotomic(f, factor=False):
    """Compute roots of cyclotomic polynomials."""
    L, U = _inv_totient_estimate(f.degree())

    for n in range(L, U + 1):
        g = cyclotomic_poly(n, f.gen, polys=True)

        if f == g:
            break
    else:  # pragma: no cover
        raise RuntimeError("failed to find index of a cyclotomic polynomial")

    roots = []

    if not factor:
        # get the indices in the right order so the computed
        # roots will be sorted
        h = n//2
        ks = [i for i in range(1, n + 1) if math.gcd(i, n) == 1]
        ks.sort(key=lambda x: (x, -1) if x <= h else (abs(x - n), 1))
        d = 2*I*pi/n
        for k in reversed(ks):
            roots.append(exp(k*d).expand(complex=True))
    else:
        g = Poly(f, extension=root(-1, n))

        for h, _ in ordered(g.factor_list()[1]):
            roots.append(-h.TC())

    return roots
Esempio n. 28
0
File: misc.py Progetto: peteut/migen
def gcd_multiple(numbers):
    l = len(numbers)
    if l == 1:
        return numbers[0]
    else:
        s = l // 2
        return gcd(gcd_multiple(numbers[:s]), gcd_multiple(numbers[s:]))
def max_points(points):
    """
    Given n points on a 2D plane,
    find the maximum number of points that lie on the same straight line.
    """
    if len(points) < 3:
        return len(points)

    global_max = 0
    for i in range(len(points) - 1):
        local_max = 1
        num_same_point = 0
        num_point_in_vertical = 1
        slope_record = {}
        for j in range(i + 1, len(points)):
            if points[i].x == points[j].x:
                if points[i].y == points[j].y:
                    num_same_point += 1
                else:
                    num_point_in_vertical += 1
            else:
                dy = points[j].y - points[i].y
                dx = points[j].x - points[i].x
                factor = gcd(dy, dx)
                slope = str(dy / factor) + "/" + str(dx / factor)
                slope_record[slope] = slope_record.get(slope, 2) + 1
                local_max = max(slope_record[slope], local_max)
        local_max = max(
            local_max + num_same_point,
            num_same_point + num_point_in_vertical)
        global_max = max(global_max, local_max)
    return global_max
Esempio n. 30
0
def count_fractions_in_range(bottom, top, limit):
    """
    Counts the number of irreducible fractions n/d for
    all 1 ≤ d ≤ limit and n ≤ d between bottom and top,
    where bottom and top are fractions.
    """
    count = 0
    for d in range(1, limit + 1):
        # Find first fraction n/d > bottom.
        m = bottom.numerator * d
        if m % bottom.denominator == 0:
            n = int(m / bottom.denominator) + 1
        else:
            n = int(m / bottom.denominator + 1.0)

        # Find last fraction n/d < top
        y = top.numerator * d
        if y % top.denominator  == 0:
            z = int(y / top.denominator) - 1
        else:
            z = int(y / top.denominator)


        for i in range(n, z + 1):
            if gcd(i, d) == 1:
                count += 1

    return count
Esempio n. 31
0
def are_coprimes(a, b):
    return math.gcd(a, b) == 1
Esempio n. 32
0
import math
while True:
    try:
        a, b = map(int,input().split())
        print("{} {}".format(math.gcd(a,b),(a * b) // math.gcd(a, b)))
    except: break
import math
number_of_test_cases = int(input())

for i in range(number_of_test_cases):
    array = [int(i) for i in input().split()]
    amount = array[0]

    j = 1
    gdc_sum = 0
    while j <= amount:
        k = j + 1
        while k <= amount:
            gdc_sum += math.gcd(array[j], array[k])
            k += 1
        j += 1
    print(gdc_sum)
Esempio n. 34
0
import math

a, b, n = map(int, input().split())
i = 0
while n >= 0:
    n -= math.gcd(n, (a, b)[i])
    i = 1 - i
print(i)
Esempio n. 35
0
    if not (ax == bx and ay == by):
        diffx = bx - ax
        diffy = by - ay
        if diffx == 0:
            sign = 1 if diffy > 0 else -1
            if not any(
                (ax, ay + y * sign) in astroids for y in range(1, abs(diffy))):
                sees.add((bx, by))
                print(bx, by)
        elif diffy == 0:
            sign = 1 if diffx > 0 else -1
            if not any(
                (ax + x * sign, ay) in astroids for x in range(1, abs(diffx))):
                sees.add((bx, by))
        else:
            gcd = math.gcd(abs(diffx), abs(diffy))
            minDiffx = diffx // gcd
            minDiffy = diffy // gcd
            if not any((ax + minDiffx * i, ay + minDiffy * i) in astroids
                       for i in range(1, gcd)):
                sees.add((bx, by))

# def left_turn(p, q, r):
#     """ Check if r is to the left of the line through p and q
#     """
#     return (q[0]-p[0]) * (r[1]-p[1]) - (r[0]-p[0]) * (q[1]-p[1]) >= 0


def getAngle(a, b, c):
    ang = math.degrees(
        math.atan2(c[1] - b[1], c[0] - b[0]) -
Esempio n. 36
0
import math
f3, g3 = map(int, input().split())
sp1 = []
bb1 = list(map(int, input().split()))
for j in range(0, g3):
    l1, h1 = map(int, input().split())
    sp1.append([l1, h1])
for j in sp1:
    ss1 = j[0] - 1
    oo1 = j[1] - 1
    print(math.gcd(bb1[ss1], bb1[oo1]))
Esempio n. 37
0
#for i in range(int(input())):
#    input()
#    a = list(map(int,input().split()))
#    for i in a[1:]:
#        while i:
#            a[0], i = i, a[0]%i
#    print(0 if a[0] == 1 else -1)
from math import gcd
for i in range(int(input())):
    input()
    a = list(map(int,input().split()))
    for i in a[1:]:
        a[0] = gcd(a[0],i)
        if a[0] == 1: #once one = always one :)
            break
    print(0 if a[0] == 1 else -1)
        
Esempio n. 38
0
import math
import random

print(math.fabs(-15.54))
print(math.sqrt(100))
print(math.floor(15.54))
print(math.ceil(15.54))
print(math.factorial(5))
print(math.gcd(30, 72))
print(random.randint(1, 100))
def _lcm(a, b):
    return (a * b) // math.gcd(a, b)
Esempio n. 40
0
 def lcm(numbers):
     '''Helper to compute the Least Commom Multiple'''
     return reduce(lambda a, b: a * b // gcd(a, b), numbers)
Esempio n. 41
0
def lcm(x, y):
    return (x*y)//math.gcd(x,y)
Esempio n. 42
0
def lcm(a, b):
    return a * b // math.gcd(a, b)
Esempio n. 43
0
def lcm(x, y):
    return int(x * y / gcd(x, y))
Esempio n. 44
0
def lcm(x, y):
    return abs(x * y) // gcd(x, y)
Esempio n. 45
0
def simplify(x, y):
    g = gcd(x, y)
    return Fraction(int(x / g), int(y / g))
Esempio n. 46
0
def get_group_generators(p) -> List[int]:
    """
    Is the size of the group which is all number below p
    which is relative prime with p
    """
    return list(filter(lambda x: math.gcd(x, p) == 1, range(p)))
Esempio n. 47
0
        S_two.append(result)
    count += 1

for i in range(len(S_zero)):
    if S_zero[i] != -1:
        for j in range(len(S_zero)):
            if y_power_list[i] > y_power_list[j]:
                big = y_power_list[i] - y_power_list[j]
                small = g_power_list[j] - g_power_list[i]
            else:
                big = y_power_list[j] - y_power_list[i]
                small = g_power_list[i] - g_power_list[j]

            if (S_zero[i] == S_zero[j]) and (i != j):
                if (i % 2 == 1 and j % 2 == 1) or (i % 2 == 0 and j % 2 == 0):
                    d = math.gcd(big % (k - 1), (k - 1))
                    b = (small) % (k - 1)
                    a = big % (k - 1)
                    modulus_operation(a, b, (k - 1), i, j)
                elif (i % 2 == 1 or i % 2 != 0) and (j % 2 == 0 or j % 2 == 1):
                    d = math.gcd(big, (k - 1))
                    b = (small + 1) % (k - 1)
                    a = big % (k - 1)
                    modulus_operation(a, b, (k - 1), i, j)

if len(answer) == 0:
    for i in range(len(S_one)):
        if S_one[i] != -1:
            for j in range(len(S_one)):
                if y_power_list[i] > y_power_list[j]:
                    big = y_power_list[i] - y_power_list[j]
Esempio n. 48
0
def euler_phi(n):
    return sum(gcd(n, k) == 1 for k in range(1, n + 1))
Esempio n. 49
0
def GCD(n1, n2):
    return math.gcd(n1, n2)
Esempio n. 50
0
def lcm(a, b):
    return abs(a * b) // math.gcd(a, b)
Esempio n. 51
0
def bigrun(maxM, maxS):
    for m in range(1, maxM + 1):
        for s in range(1, maxS + 1):  #7, maxS+1):
            if m > s + 1:
                if math.gcd(m, s) == 1:
                    yield getRow(m, s)
def commandLineArguments():

    cipher = sys.argv[1]

    ## shift cipher ##
    if (cipher == 'shift'):
        temp = sys.argv[2]
        if (temp == 'encrypt'):
            inputFile = open(sys.argv[3], 'r')
            outputFile = open(sys.argv[4], 'w')

            k = int(sys.argv[5])

            inputLines = inputFile.readlines()

            for line in inputLines:
                outputFile.write(encryptShiftCipher(line, k))
            inputFile.close()
            outputFile.close()

        elif (temp == 'decrypt'):
            inputFile = open(sys.argv[3], 'r')
            outputFile = open(sys.argv[4], 'w')

            k = int(sys.argv[5])

            inputLines = inputFile.readlines()

            for line in inputLines:
                outputFile.write(decryptShiftCipher(line, k))
            inputFile.close()
            outputFile.close()

        else:
            print(
                "no mode defined for shift cipher either \'encrypt\' or \'decrypt\'"
            )

    ## vigenere cipher ##
    elif (cipher == 'vigenere'):
        temp = sys.argv[2]
        if (temp == 'encrypt'):
            inputFile = open(sys.argv[3], 'r')
            outputFile = open(sys.argv[4], 'w')

            k = str(sys.argv[5])

            inputLines = inputFile.readlines()

            for line in inputLines:
                outputFile.write(encryptVigenereCipher(line, k))
            inputFile.close()
            outputFile.close()

        elif (temp == 'decrypt'):
            inputFile = open(sys.argv[3], 'r')
            outputFile = open(sys.argv[4], 'w')

            k = str(sys.argv[5])

            inputLines = inputFile.readlines()

            for line in inputLines:
                outputFile.write(decryptVigenereCipher(line, k))
            inputFile.close()
            outputFile.close()

        else:
            print(
                "no mode defined for vigenere cipher either \'encrypt\' or \'decrypt\'"
            )

    ## affine cipher ##
    elif (cipher == 'affine'):
        temp = sys.argv[2]
        if (temp == 'encrypt'):

            a = int(sys.argv[5])
            b = int(sys.argv[6])

            if math.gcd(a, 26) != 1:
                print("invalid \'a\' : a and 26 aren't coprime")
                sys.exit()

            inputFile = open(sys.argv[3], 'r')
            outputFile = open(sys.argv[4], 'w')

            inputLines = inputFile.readlines()

            for line in inputLines:
                outputFile.write(encryptAffineCipher(line, a, b))
            inputFile.close()
            outputFile.close()

        elif (temp == 'decrypt'):
            a = int(sys.argv[5])
            b = int(sys.argv[6])

            if math.gcd(a, 26) != 1:
                print("invalid \'a\' : a and 26 aren't coprime")
                sys.exit()

            inputFile = open(sys.argv[3], 'r')
            outputFile = open(sys.argv[4], 'w')
            inputLines = inputFile.readlines()

            for line in inputLines:
                #print(line)
                outputFile.write(decryptAffineCipher(line, a, b))
            inputFile.close()
            outputFile.close()

        else:
            print(
                "no mode defined for Affine cipher either \'encrypt\' or \'decrypt\'"
            )

    else:
        print(
            "ERROR no cipher is given either \'shift\' or \'affine\' or \'vigenere\'"
        )
Esempio n. 53
0
def lcm(x, y):
    return x * y // gcd(x, y)
Esempio n. 54
0
 def canMeasureWater(x: int, y: int, z: int) -> bool:
     """
     :param x: X壶的水容量
     :param y: Y壶的水容量
     :param z: 目标Z升水
     :return: 是否能成功
     """
     """
     强行在纸上推导了好久...不知道贝祖定理啊!
     我是分了好多种情况讨论的...心累-_-|||
     虽然通过了,但代码很烂...不想再看第二遍hhh
     不过还是强行记下这个定理吧:(百度百科)
     裴蜀定理(或贝祖定理)得名于法国数学家艾蒂安·裴蜀,说明了对任何整数a、b和它们的最大公约数d,关于未知数x和y的线性不定方程(称为裴蜀等式):
     若a,b是整数,且gcd(a,b)=d,那么对于任意的整数x,y,ax+by都一定是d的倍数,特别地,一定存在整数x,y,使ax+by=d成立。
     它的一个重要推论是:a,b互质的充要条件是存在整数x,y使ax+by=1.
     """
     if x + y < z or z < 0:
         return False
     if x + y == z or z == 0:
         return True
     if x == 0 and y == 0 and z != 0:
         return False
     if x == 0 and y != 0 and z != 0:
         return True if z % y == 0 else False
     if y == 0 and x != 0 and z != 0:
         return True if z % x == 0 else False
     if z % x == 0 or z % y == 0:
         return True
     if gcd(y, x) * gcd(z, x) == 1:
         return True
     if gcd(y, x) == gcd(z, x) and 1 not in [gcd(y, x), gcd(z, x)]:
         return True
     if gcd(y, x) != gcd(z, x) and 1 not in [gcd(y, x), gcd(z, x)]:
         return False
     if gcd(y, x) == 1 and gcd(z, x) != 1:
         return True
     if gcd(y, x) != 1 and gcd(z, x) == 1:
         return False
def lcm(a,b):
    return a*b//gcd(a,b)
def lcm(a, b):
    a, b = int(a), int(b)
    return int(abs(a * b) / math.gcd(a, b))
Esempio n. 57
0
import math
num = int(input())
array = list(map(lambda x: math.gcd(num, x), [i for i in range(1, num + 1)]))
print(array.count(1))
Esempio n. 58
0
import math
a = int(input("Enter First Number: "))
b = int(input("Enter Second number: "))
s = math.gcd(a, b)
print("GCD of", a, "&", b, "is: ", s)
Esempio n. 59
0
def vAdd(a, b):
    return (a[0] + b[0], a[1] + b[1])


def vDiv(a, d):
    return (a[0] // d, a[1] // d)


highscore = (0, 0)
for a in astdict:
    score = 0
    for b in astdict:
        if b != a:
            v = vSub(b, a)
            gcd = math.gcd(v[0], v[1])
            v = vDiv(v, gcd)
            cursor = vAdd(a, v)
            while not cursor in astdict:
                cursor = vAdd(cursor, v)
            if cursor == b:
                score += 1
    astdict[a] = score
    if score > highscore[1]:
        highscore = (a, score)

#if X and Y have a common divisor,

20, 30

2, 3
# 최대공약수와 최소공배수
# 유클리드 호제법

import math

A, B = map(int, input().split())
gcd = math.gcd(A, B)

print(gcd)
print(A * B // gcd)
"""
24 18
"""