Exemplo n.º 1
0
def test(a, b):
    div = utils.gcd(a, b)
    a1 = a // div
    b1 = b // div

    a2_str = ''
    b2_str = str(b)
    has_common = False
    for c in str(a):
        if c != '0':
            if c in str(b):
                has_common = True
                b2_str = b2_str.replace(c, '')
            else:
                a2_str += c
    if not has_common or a2_str == '' or b2_str == '':
        return False
    a2 = int(a2_str)
    b2 = int(b2_str)
    if a2 == 0 or b2 == 0:
        return False
    div2 = utils.gcd(a2, b2)
    a3 = a2 // div2
    b3 = b2 // div2

    return a1 == a3 and b1 == b3
Exemplo n.º 2
0
def pollard_p_minus_one(n, b=5, m=13, a=2):
    if b < 1:
        raise Exception('B must be bigger than 1')
    if b >= m:
        raise Exception('B must be less than sqrt(n)')
    if m >= b**2:
        raise Exception('M must be less than B^2')
    if m >= math.sqrt(n):
        raise Exception('M must be less than sqrt(n)')
    if a < 1:
        raise Exception('a must be bigger than 1')

    mb_primes = utils.primes(2, b)
    primes_mul = reduce(operator.mul, mb_primes, 1)

    b = (a**primes_mul) % n
    q = utils.gcd(b - 1, n)

    if q > 1:
        return q, n // q

    m_primes = utils.primes(b, m)
    for m in m_primes:
        fm = (b**(m - 1)) % n
        gm = utils.gcd(fm, n)
        if gm > 1:
            return gm, n // gm

    return math.nan, math.nan
Exemplo n.º 3
0
def pollard_po(n, func=lambda x: x**2 + 1):
    x = random.randint(1, n - 2)
    y = 1
    i = 1
    stage = 2

    while utils.gcd(n, x - y) == 1:
        if i == stage:
            y = x
            stage *= 2

        x = func(x) % n
        i += 1

    d = utils.gcd(n, x - y)
    b = n // d

    res = [d]

    if not utils.is_prime(b):
        b1, b2 = pollard_po(b)
        res.append(b1)

        if isinstance(b2, tuple):
            res.append(b2[0])
            res.append(b2[1])
        else:
            res.append(b2)
        return res

    res.append(b)
    return res
Exemplo n.º 4
0
def isprime(p):
    q = p - 1
    m = 0
    while q & 1 == 0:
        m += 1
        q //= 2
    s = q

    r = 0
    while r < miller_rabin_tests_count:
        a = random.randint(2, p - 2)
        while gcd(a, p) > 1:
            a = random.randint(2, p - 2)
        b = pow(a, s, p)
        if b == 1:
            continue
        elif b == p - 1:
            r += 1
            continue

        for l in range(1, m):
            c = pow(a, s * pow(2, l), p)
            if c == p - 1:
                r += 1
                break
        else:
            return False
    return True
Exemplo n.º 5
0
    def __init__(self, hypervector=None, multiplier=None, modulus=None):
        '''
        Реализира кодирането на Merkle-Hellman,
        използващо алгоритъма за раницата.
        Конструкторът приема хипернарастващ вектор,
        число, по което се умножават елементите му
        и модул(последните две се използват за генериране на публичния ключ).
        '''

        # Ако тези стойности не са дадени, произволни ще бъдат автоматично генерирани.
        if not multiplier:
            for x in range(modulus):
                if gcd(x, modulus) == 1:
                    self.multiplier = x
                    break
        else:
            self.multiplier = multiplier

        self.private_key = hypervector
        sum_vector = sum(hypervector)
        self.modulus = modulus or randint(sum_vector + 1, sum_vector * 2)
        if self.modulus < sum_vector:
            print('''Внимание! Кодирането се извършва по модул,
по-малък от сумата на числата във хипернарастващия вектор!
Това **ще** доведе до грешки и е силно непрепоръчително!''')

        self.public_key = [(element * multiplier) % modulus
                           for element in hypervector]
Exemplo n.º 6
0
    def __init__(self, hypervector = None, multiplier = None, modulus = None):
        '''
        Реализира кодирането на Merkle-Hellman,
        използващо алгоритъма за раницата.
        Конструкторът приема хипернарастващ вектор,
        число, по което се умножават елементите му
        и модул(последните две се използват за генериране на публичния ключ).
        '''
 
        # Ако тези стойности не са дадени, произволни ще бъдат автоматично генерирани.
        if not multiplier:
            for x in range(modulus):
                if gcd(x, modulus) == 1:
                    self.multiplier = x
                    break
        else:
            self.multiplier = multiplier
 
        self.private_key = hypervector
        sum_vector = sum(hypervector)
        self.modulus = modulus or randint(sum_vector + 1, sum_vector * 2)
        if self.modulus < sum_vector:
            print('''Внимание! Кодирането се извършва по модул,
по-малък от сумата на числата във хипернарастващия вектор!
Това **ще** доведе до грешки и е силно непрепоръчително!''')
 
        self.public_key = [(element * multiplier) % modulus for element in hypervector]
Exemplo n.º 7
0
def run():
    """
    Solution: Since we are dealing with only 2 digit numbers,
    a brute force search is not so bad.
    """
    top, bottom = 1, 1

    for d in xrange(10, 100):
        for n in xrange(10, d):
            # extract digits as strings
            ns, ds = set(str(n)), set(str(d))

            # we need exactly one overlap
            if len(ds) is 1 or len(ns) is 1:
                continue

            # skip if there are no shared digits or if shared 0
            common = ds.intersection(ns)
            if len(common) is not 1 or str(0) in common:
                continue

            # compute the new fraction after removal of common digit
            denominator = float("".join(ds.difference(common)))
            if denominator < 1:
                continue
            numerator = float("".join(ns.difference(common)))

            # compare it to the original fraction
            a = float(n) / float(d)
            b = numerator / denominator
            if abs(a - b) < 0.000001:
                top *= n
                bottom *= d

    return bottom / gcd(top, bottom)
Exemplo n.º 8
0
def gen_relatively_prime(size):
    q = gen_odd(size)
    while utils.gcd(q, SMALL_PRIMES_PRODUCT) > 1 or q % 4 != 3:
        q += 2
        if not check_len(q, size):
            q = gen_odd(size)
    return q
Exemplo n.º 9
0
def p33():

    def check(no, de):
        digit_in_de = {digit for digit in str(denominator)}
        digit_in_no = {digit for digit in str(nominator)}
        same_digit = digit_in_de.intersection(digit_in_no)
        digit_in_de = digit_in_de - same_digit
        digit_in_no = digit_in_no - same_digit

        if "0" in same_digit or len(same_digit) != 1:
            return False

        if not digit_in_de or not digit_in_no or "0" in digit_in_de:
            return False

        if float(digit_in_no.pop()) / float(digit_in_de.pop()) == \
                float(nominator) / float(denominator):
            return True

    target_de = 1
    target_no = 1
    for denominator in range(12, 100):
        for nominator in range(11, denominator):
            if not check(nominator, denominator):
                continue
            target_no *= nominator
            target_de *= denominator

    return target_de / gcd(target_de, target_no)
Exemplo n.º 10
0
def gen_relatively_prime(size):
    q = gen_odd_q(size)

    while gcd(q, mul_small_primes) > 1 or q % 4 != 3:
        q += 2
        if not check_len(q, size):
            q = gen_odd_q(size)

    return q
Exemplo n.º 11
0
 def signing(self, message):
     m = self.__encode_md5(message)
     self.K = random.randint(1, self.q-1)
     while gcd(self.K, self.q-1) != 1:
         self.K = random.randint(1, self.q-1)
     
     s1 = pow(self.a, self.K, self.q)
     s2 = modinv(self.K, self.q-1)*(m - self.X*s1)%(self.q-1)
     return s1, s2
Exemplo n.º 12
0
def main():
    min_dist = Fraction(3 / 7)
    for d in range(2, 10**6 + 1):
        n = ceil(d * 3 / 7) - 1
        if gcd(n, d) == 1:
            dist = Fraction(3, 7) - Fraction(n, d)
            if dist < min_dist:
                min_dist = dist
                closest_fraction = Fraction(n, d)
    print(closest_fraction.numerator)
Exemplo n.º 13
0
 def remove(x,y):
     if(inv[x][y] == 0):
         #if(x<len(inv)-1):
         #    inv[x], inv[x+1] = inv[x+1].copy(), inv[x].copy()
         #print inv
         return
     GCD = gcd(inv[x][y], inv[y][y])
     LCM = inv[x][y]*inv[y][y]/GCD
     a = LCM / inv[x][y]
     b = LCM / inv[y][y]
     inv[x] = inv[x]*a - inv[y]*b
Exemplo n.º 14
0
def factorize_rho(n, verbose=False):
    if n == 1 or utils.is_prime(n):
        return n

    # If no factor is found, return -1
    for i in range(len(small_primes) - 1, -1, -1):
        r, c, y = 1, small_primes[i], random.randint(1, n - 1)
        if verbose:
            print "Trying offset:", c

        m, g, q, ys = random.randint(1, n - 1), 1, 1, y
        min_val, k = 0, 0
        while g == 1:
            x, k = y, 0
            for j in range(r):
                y = y * y + c
                if y > n: y %= n
            while k < r and g == 1:
                ys, min_val = y, min(m, r - k)
                for j in range(min_val):
                    y = y * y + c
                    if y > n: y %= n
                    q = q * abs(x - y)
                    if q > n: q %= n
                g = utils.gcd(q, n)
                k += m
            r <<= 1

        if g == n:
            # If no factor found, try again.
            while True:
                ys = ys * ys + c
                if ys > n: ys %= n
                g = utils.gcd(abs(x - ys), n)
                if g > 1:
                    break

        if g != n:
            return g
        else:
            return -1
Exemplo n.º 15
0
Arquivo: 183.py Projeto: AlexClowes/pe
def D(N):
    k = floor(N / e)
    if k * log(N / k) < (k + 1) * log(N / (k + 1)):
        k += 1
    k //= gcd(N, k)
    while k % 2 == 0:
        k //= 2
    while k % 5 == 0:
        k //= 5
    if k == 1:
        return -N
    return N
def original_solution():
    """runtime on mbp is: 31s, yikes. Solution based on #71
        Want to just take 1/3 of the sequence length (calculated using #72), which is really close, but off by 4
    """
    N = 12000
    # from the data given, we know that we can do at least 2/5ths, use that as a starting point
    start, end = (1.0/3.0), (1.0/2.0)
    count = 0
    for base in xrange(1, N+1):
        for n in xrange(int(start*base), int(end * base)+1):
            if start < (float(n) / base) < end and gcd(n, base) == 1:
                count += 1
    return count
def original_solution():
    """runtime on mbp is: 31s, yikes. Solution based on #71
        Want to just take 1/3 of the sequence length (calculated using #72), which is really close, but off by 4
    """
    N = 12000
    # from the data given, we know that we can do at least 2/5ths, use that as a starting point
    start, end = (1.0 / 3.0), (1.0 / 2.0)
    count = 0
    for base in xrange(1, N + 1):
        for n in xrange(int(start * base), int(end * base) + 1):
            if start < (float(n) / base) < end and gcd(n, base) == 1:
                count += 1
    return count
Exemplo n.º 18
0
def main():
    max_perimeter = 10**8
    count = 0
    for m in range(2, int((max_perimeter / 2)**0.5) + 1):
        for n in range(m - 1, 0, -2):
            if gcd(m, n) == 1:
                a = m * m - n * n
                b = 2 * m * n
                c = m * m + n * n
                c = (m + n) * (m + n) - b
                if c % abs(b - a) == 0:
                    count += max_perimeter // (a + b + c)
    print(count)
Exemplo n.º 19
0
def p071():
    LIMIT = 1000000

    best_diff = 1.0/35
    best_n = 0
    for d in xrange(8,LIMIT+1):
        n = d * 3 / 7
        if gcd(n,d) == 1:
            diff = 3.0/7.0 - n*1.0/d
            if diff < best_diff:
                best_diff = diff
                best_n = n

    return best_n
Exemplo n.º 20
0
def factor(n=256961):
    base = [-1] + [x for x in range(2, 32) if is_prime(x)]
    start = int(n**.5)
    pairs = []

    for i in range(start, n):
        for j in base:
            if i**2 % n == j**2 % n:
                pairs.append([i, j])

    for i in pairs:
        factor = gcd(i[0] - i[1], n)
        if factor != 1:
            return factor, n // factor
Exemplo n.º 21
0
    def mul_inv_int(self, num, mode = 'bezout'):
        num = int_check_strict(num, ZN_ERR_MSG_NUM)
        n = self.n

        g = gcd(num, n)
        if g > 1:
            return ZN_ERR_MSG_INV.format(a = num, n = n, gcd = g)

        if mode == 'bezout':
            _, inv, _ = bezout(num % n, n)
            return inv % n
        elif mode == 'euler':
            return self.pow_int(num, self.totient() - 1)
        else:
            raise ValueError
Exemplo n.º 22
0
def optimized_solution():
    """optimized_solution took 638.455 ms"""
    N = 1500*1000 
    sqrt_N = int(N**.5) + 1
    wires = [0] * (N+1) # array = hash for ints. This saves about a second.
    
    for m in xrange(1, sqrt_N):
        start = 2 if (m & 1) else 1 # if m is even, n is odd, and vice versa
        end = min(m, 1 + int(N / 2.0 / m) - m) # choose the end so that the max perimeter is <= N
        for n in xrange(start, end, 2):
            if gcd(n, m) == 1: # primitive
                perimeter = 2*m*(m + n)
                for p in xrange(perimeter, N+1, perimeter):
                    wires[p] += 1
    
    return wires.count(1)
Exemplo n.º 23
0
def main():
    n_max = 10**12
    total = 0
    for a in range(2, floor(n_max**(1 / 3))):
        for b in range(1, a):
            if ((a % 2 == 1 or b % 2 == 1) and (a % 3 != 0 or b % 3 != 0)
                    and gcd(a, b) == 1):
                c = 1
                while True:
                    n = b * c * (a**3 * c + b)
                    if n > n_max:
                        break
                    if is_square(n):
                        total += n
                    c += 1
    print(total)
Exemplo n.º 24
0
def main():
    print 'task 33'
    prod_a = 0
    prod_b = 0
    for a in range(10, 99):
        for b in range(a + 1, 100):
            if test(a, b):
                print '(%d)/(%d)' % (a, b)
                if prod_a == 0:
                    prod_a = a
                    prod_b = b
                else:
                    prod_a *= a
                    prod_b *= b
    div = utils.gcd(prod_a, prod_b)
    print (prod_b // div)
Exemplo n.º 25
0
def compute_phi(n, sieve=None):
    if n % 2 == 0:
        if n / 2 % 2 == 0:
            phi = 2 * cache[n / 2]
        else:
            phi = cache[n / 2]
    elif sieve and sieve[n]:
        phi = n - 1
    else:
        for a in xrange(2, int(math.sqrt(n)) + 1):
            if n % a == 0:
                b = n / a
                c = gcd(a, b)
                phi = cache[a] * cache[b] * c / cache[c]
                break
    cache[n] = phi
    return phi
Exemplo n.º 26
0
 def skfunc(U, n):
     if n == 0:
         M = U.full()
         v = np.array([[np.real(M[0, 0]), np.imag(M[0, 0]), np.real(M[1, 0]), np.imag(M[1, 0])]])
         dist, index = tree['tree'].query(v, k=1)
         name = tree['names'][index[0, 0]]
         if name == '':
             return gate.I
         else:
             basis = tree['basis']
             return multiply([basis[int(x)] for x in name])
     else:
         U_next = skfunc(U, n - 1)
         V, W = gcd(U * U_next.dag())
         V_next = skfunc(V, n - 1)
         W_next = skfunc(W, n - 1)
         return V_next * W_next * V_next.dag() * W_next.dag() * U_next
Exemplo n.º 27
0
def convergent(coeffs, N):
    if N == 0:
        return coeffs[0]
    n, d = 0, 0
    while N > 0:
        c = coeffs[N]
        if d is 0:
            n = 1
            d = c
        else:
            temp = n
            n = d
            d = temp + c * d
        N -= 1
    n = coeffs[0] * d + n
    g = gcd(n, d)
    return n / g, d / g
Exemplo n.º 28
0
def M(n, k):
    if gcd((pow(2, n, n) - 1) % n, n) == 1:
        # if gcd((2**n-1)%n, n) is 1, then we are definitely already reduced!
        # this is because gcd(2**n-1, (2**n-1)*(k-1)+n) == gcd(2**n-1,n) == gcd((2**n-1)%n, n)
        pass
    else:
        # otherwise, I don't know how to guarantee that gcd((2**n-1)**2, (2**n-1)*(k-1)+n) == gcd(2**n-1, (2**n-1)*(k-1)+n),
        # in which case things become messier since some factors of the latter could possibly be duplicated in the gcd.
        # fortunately this doesn't happen for the input requested by PE. If it did, one possibility is to find the gcd
        # gcd(2**n-1, n) with gcd(k-1, n) -- I haven't proved it but I think these factors would be replicated in both
        # numerator and denominator.
        raise Exception(
            "we maybe need more heavy lifting because of the square in the denominator"
        )
    x = (pow(2, n, mod) - 1) % mod
    numerator = pow(2, n - k, mod) * ((k - 1) * x % mod + n) % mod
    denominator = pow(x, 2, mod) % mod
    return numerator * denominator % mod
Exemplo n.º 29
0
def count_quadrilaterals(m):
    gcd_vals = np.zeros((m, m))
    for i in range(m):
        for j in range(m):
            gcd_vals[i, j] = gcd(i + 1, j + 1)

    count = 0
    for a in range(1, m + 1):
        for b in range(1, m + 1):
            for c in range(1, m + 1):
                for d in range(1, m + 1):
                    area_term = a * b + b * c + c * d + d * a
                    edge_term = (gcd_vals[a - 1, b - 1] +
                                 gcd_vals[b - 1, c - 1] +
                                 gcd_vals[c - 1, d - 1] +
                                 gcd_vals[d - 1, a - 1])
                    count += is_square((area_term - edge_term) // 2 + 1)
    return count
def original_solution():
    """runtime on mbp is 93ms. 
        This is another case (I'm looking at you, #70) of decreasing runtime by looking
        where the answer is and returning. Searching the whole space takes considerably longer.
    """
    N = 1000*1000
    
    # from the data given, we know that we can do at least 2/5ths, use that as a starting point
    frac, best, three_sevenths = .4, 2, (3.0/7.0)
    
    for base in xrange(N, N-10, -1): # I bet we'll find it within 10 loops
        for n in xrange(int(frac*base), int(three_sevenths * base)):
            if frac < (float(n)/base) and gcd(n, base) == 1:
                best = n
                frac = float(n) / base
                #print "best: (%d / %d) " % (n, base)
    
    return best
Exemplo n.º 31
0
def euclid_pythagorean_triple():
    return_type = namedtuple('Data', 'abc a b c')
    primes = prime_factors(500)
    all_combinations = set([1])  # Not returned as a prime

    for i in range(1, len(primes) + 1):
        all_combinations.update(
            [product(tuple_) for tuple_ in combinations(primes, i)])

    valid_set = sorted(all_combinations)

    for k in valid_set:
        for n, i in enumerate(valid_set):
            for m in valid_set[i:]:
                if gcd(m, n) == 1 and k * m * (m + n) == 500:
                    return return_type(k**3 * 2 * m * (m**4 - n**4),
                                       k * (m**2 - n**2), 2 * m * n * k,
                                       k * (m**2 + n**2))
Exemplo n.º 32
0
    def mul_inv(self, mode = 'bezout'):
        """
        mode='bezout' or 'euler'
        """
        n = self.n
        a = self.reduced

        g = gcd(a, n)
        if g > 1:
            return ZN_ERR_MSG_INV.format(a = self.original, n = n, gcd = g)

        if mode == 'bezout':
            _, inv, _ = bezout(a, n)
            return ZnNumber(inv % n, n)
        elif mode == 'euler':
            return self ** (ZnNumber.totient(n) - 1)
        else:
            raise ValueError
def original_solution():
    """runtime on mbp is 93ms. 
        This is another case (I'm looking at you, #70) of decreasing runtime by looking
        where the answer is and returning. Searching the whole space takes considerably longer.
    """
    N = 1000 * 1000

    # from the data given, we know that we can do at least 2/5ths, use that as a starting point
    frac, best, three_sevenths = .4, 2, (3.0 / 7.0)

    for base in xrange(N, N - 10, -1):  # I bet we'll find it within 10 loops
        for n in xrange(int(frac * base), int(three_sevenths * base)):
            if frac < (float(n) / base) and gcd(n, base) == 1:
                best = n
                frac = float(n) / base
                #print "best: (%d / %d) " % (n, base)

    return best
Exemplo n.º 34
0
def legendre(a, p):
    """
    источник: Маховенко Е.Б. 'Теоретическая криптография', стр. 83
    :return: значение символа Лежандра (1, -1, 0)
    """
    a %= p
    if a % p == 0:
        return 0
    if utils.gcd(a, p) != 1:
        raise ArithmeticError(
            'Символ Лежандра имеет смысл для взаимно простых a и p')

    q = pow(a, (p - 1) // 2, p)
    if q == 1:
        return 1
    elif q == p - 1:
        return -1
    else:
        raise ArithmeticError('Неверно вычислен символ Лежандра')
Exemplo n.º 35
0
def GenRSA(n: int, tries=200, dictionary={}):
    N, p, q = GenModulus(n, tries)
    phi_n = (p - 1) * (q - 1)

    e = random.randint(5000, 500_000)
    # e = random.choice(PRIMES)
    while gcd(e, phi_n) > 1:
        e = random.randint(5000, 500_000)
        # print(e, phi_n)
        # input()
    d = modInverse(e, phi_n)


    dictionary['n'] = N
    dictionary['e'] = e
    dictionary['d'] = d
    dictionary['p'] = p
    dictionary['q'] = q

    return N, e, d
Exemplo n.º 36
0
def array_rotation(array=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
                   rotate_till_element=3):
    # So take the gcd of Len. of array and elem.
    # to rotate and make pairs, shift pairwise elements
    pairs = gcd(len(array), rotate_till_element)
    temp = array[0]
    starting_posi = 0
    while (rotate_till_element > 0):
        temp = array[starting_posi]
        num = starting_posi
        try:
            while num < len(array):
                array[num] = array[num + pairs]
                num += pairs
                print(num)
        except Exception as e:
            array[num] = temp
        starting_posi += 1
        rotate_till_element -= 1
    return array
Exemplo n.º 37
0
def angled_below_diagonal(size):
    count = 0
    for x in xrange(1,size):
        for y in xrange(1,x):
            if gcd(x,y) > 1: continue
            m1 = 1
            while x*m1 <= size and y*m1 <= size:
                p1x, p1y = x*m1, y*m1
                m2 = 1
                while p1x + m2*y <= size and p1y - m2*x >= 0:
                    count += 1
                    # print ((p1x, p1y, p1x+m2*y, p1y-m2*x))
                    m2 += 1
                m2 = 1
                while p1x - m2*y >= 0 and p1y + m2*x <= size:
                    count += 1
                    # print ((p1x, p1y, p1x-m2*y, p1y+m2*x))
                    m2 += 1
                m1 += 1
    return count
Exemplo n.º 38
0
def run():
    """
    Iterate through all denominators d, then descend through numerators n
    less than 3d/7 until gcd(n,d) = 1 (reduced proper fraction). The largest
    n / d fraction obtained in this fashion for some d is the answer we are
    looking for.

    Alternatively, just realize that 7 divides 999999 evenly so the answer
    must be 999999 * 3/7 - 1.  No other fraction with d < 1000000 is closer to
    3/7 than this number.
    """
    bn, bd = 0, 1
    for d in xrange(8, 1000000):
        n = int(3 * d / 7.0)
        while gcd(n, d) > 1:
            n -= 1
        if n * bd > d * bn:
            bn = n
            bd = d
    return bn
Exemplo n.º 39
0
def main():
	print 'Task 71'

	closest = 2.0 / 5
	value = 3.0 / 7
	min_dist = value - closest
	min_dist_nom = 0
	for d in xrange(9, 1000001):
		if d % 100000 == 0:
			print d, min_dist_nom
		nom = int(d * value)
		cur_dist = value - float(nom) / d
		if cur_dist > min_dist:
			continue
		while utils.gcd(nom, d) != 1:
			nom -= 1
		cur_dist = value - float(nom) / d
		if cur_dist < min_dist:
			min_dist = cur_dist
			min_dist_nom = nom
	print min_dist_nom
Exemplo n.º 40
0
def generate_triples(total_length_limit):
    triples = set()
    max_m = int(math.sqrt((total_length_limit)//2))
    for m in xrange(1, max_m+1):
        if m % (max_m//100) == 0:
            print "%d/%d" % (m, max_m)
        max_n = (total_length_limit - 2 * m * m) // (2 * m)
        max_n = min(max_n, m-1)
        for n in xrange(1, max_n+1):
            if not ((m+n) % 2):
                continue
            if gcd(m,n) > 1:
                continue
            b = m*m - n*n
            if b < 1:
                continue
            a = 2*m*n
            c = m*m + n*n
            a,b,c = sorted([a,b,c])
            if (a + b + c) <= total_length_limit:
                triples.add((a,b,c))
    return triples
Exemplo n.º 41
0
def generate_triples(total_length_limit):
    triples = set()
    max_m = int(math.sqrt((total_length_limit)//2))
    for m in xrange(1, max_m+1):
        max_n = (total_length_limit - 2 * m * m) // (2 * m)
        max_n = min(max_n, m-1)
        for n in xrange(1, max_n+1):
            if not ((m+n) % 2):
                continue
            if gcd(m,n) > 1:
                continue
            b = m*m - n*n
            if b < 1:
                continue
            a = 2*m*n
            c = m*m + n*n
            a,b,c = sorted([a,b,c])
            s = a + b + c
            mult = 1
            while mult * s <= total_length_limit:
                triples.add((a*mult, b*mult, c*mult))
                mult += 1
    return triples
Exemplo n.º 42
0
def original_solution():
    """ original_solution took 2711.536 ms
        The answer (original) is: 161667
    """
    N = 1500*1000 
    sqrt_N = int(N**.5) + 1
    wires = defaultdict(int)
    # So, we're looking for all pythagorean triplets that sum to less than 1.5M
    # use Euclid's formula: http://en.wikipedia.org/wiki/Pythagorean_triple
    for m in xrange(1, sqrt_N):
        for n in xrange(1, m):
            if gcd(n, m) == 1 and (m+n)%2 == 1: # primitive
                sides = m**2 - n**2, 2*m*n, m**2 + n**2
                perimeter = sum(sides)
                #print "(%d, %d): %s -> %d" % (m, n, sides, perimeter)
                for p in xrange(perimeter, N+1, perimeter):
                    #print '\t', p
                    wires[p] += 1
    
    count = 0
    for p, n in wires.iteritems():
        if n == 1:
            count += 1
    return count
Exemplo n.º 43
0
def main():
    N = 12 * 10**4

    primes = list(get_primes_up_to_n(N))

    @lru_cache(maxsize=None)
    def rad(n):
        ret = 1
        for p in primes:
            if p > n:
                break
            if n % p == 0:
                ret *= p
                n //= p
        return ret

    # Possible optimisation - compute radicals and primes simultaneously
    rads = defaultdict(list)
    for n in range(1, N):
        rads[rad(n)].append(n)
    rads = sorted((rad, lst) for rad, lst in rads.items())

    total = 0
    for c in range(2, N):
        rad_c = rad(c)
        if 2 * rad_c >= c:
            continue
        for rad_a, a_vals in rads:
            if 2 * rad_a * rad_c >= c:
                break
            for a in a_vals:
                if 2 * a > c:
                    break
                if rad_a * rad(c - a) * rad_c < c and gcd(c - a, a) == 1:
                    total += c
    print(total)
Exemplo n.º 44
0
def isprime(prime):
    """
    источник: Маховенко. "Теоретическая криптография", стр. 166, алгоритм 7.7.1
    :param prime: проверяемое на простоту число
    :return: True - p простое, False - p составное
    """
    if prime & 1 == 0:
        return False

    q = prime - 1
    m = 0
    while q & 1 == 0:
        m += 1
        q //= 2
    s = q

    r = 0
    while r < MR_TESTS:
        a = random.randint(2, prime - 2)
        while utils.gcd(a, prime) > 1:
            a = random.randint(2, prime - 2)
        b = pow(a, s, prime)
        if b == 1:
            continue
        elif b == prime - 1:
            r += 1
            continue

        for l in range(1, m):
            c = pow(a, s * pow(2, l), prime)
            if c == prime - 1:
                r += 1
                break
        else:
            return False
    return True
Exemplo n.º 45
0
def mod_mul(x, dim, N=None):
    r"""Modular multiplication gate.

    U = mod_mul(x, dim)     N == prod(dim)
    U = mod_mul(x, dim, N)  gate dimension prod(dim) must be >= N

    Returns the gate U, which, operating on the computational state
    :math:`|y\rangle`, multiplies it by x (mod N):
    :math:`U |y\rangle = |x*y (mod N)\rangle`.
    x and N must be coprime for the operation to be reversible.

    If N is given, U will act trivially on computational states >= N.
    """
    # Ville Bergholm 2010-2011

    if isscalar(dim): dim = (dim,)  # scalar into a tuple
    d = prod(dim)
    if N == None:
        N = d
    elif d < N:
        raise ValueError('Gate dimension must be >= N.')

    if gcd(x, N) != 1:
        raise ValueError('x and N must be coprime for the mul operation to be reversible.')

    # NOTE: a real quantum computer would implement this gate using a
    # sequence of reversible arithmetic gates but since we don't have
    # one we might as well cheat
    U = sparse.dok_matrix((d, d))
    for y in range(N):
        U[mod(x*y, N), y] = 1
    # U acts trivially for states >= N
    for y in range(N, d):
        U[y, y] = 1

    return lmap(U.tocsr(), (dim, dim))
Exemplo n.º 46
0
def test_gcd_correctness():
    assert_equal(utils.gcd(976, 1024), 16)
    assert_equal(utils.gcd(125, 1024), 1)
    assert_equal(utils.gcd(380, 1024), 4)
Exemplo n.º 47
0
def simplify(n, d):
    x = utils.gcd(n, d)
    return n // x, d // x
Exemplo n.º 48
0
# generate our pitches
anchor_pitches = [rr(-12, 12) for _ in range(5)]
pitch_range = (-24, 18)
pc_anneal = a.annealer(temp_f=lambda t: 1 - t,
                       energy_f=pc_energy(choice(anchor_pitches),
                                          m.pitch_distance),
                       state_gen=pc_gen(choice(anchor_pitches), pitch_range[0],
                                        pitch_range[1]),
                       accept_p=a.basic_acceptance)

pcs = collect_pcs(pc_anneal, 60, 100, 10)
print("pitches collected")

# get our durations
gcd = u.gcd(60, len(pcs))
flat_pcs = [p for pc_b in pcs for p in pc_b]
bucket_durs = u.gen_equal_partitions(60, len(pcs))
pcs = u.partition_equally(gcd, flat_pcs)
pos_pcs = [[((pc % 12) + 1.0) / 24.0 for pc in pc_b] for pc_b in pcs]
durs = [[(ceil(pc * (dur / sum(pc_b))), 8) for pc in pc_b]
        for pc_b, dur in zip(pos_pcs, bucket_durs)]
print("durations generated")

# generate notes
notes_prime = [
    deepcopy(note) for pc_coll, dur_coll in zip(pcs, durs)
    for note in list(st.make_notes(pc_coll, dur_coll))
]
notes = [
    u.multiply_by(choice([3]), n)
Exemplo n.º 49
0
def Zps(N):
    """ Returns Z_p^* """
    return [n for n in range(0, N) if gcd(n, N) == 1]
Exemplo n.º 50
0
import sys
sys.path.insert(0, '../common/')
import utils
def same():
 for n in range(10,100):
  for d in range(n+1, 100):
   nd = str(n)
   dd = str(d)
   if nd[0] == dd[1] and int(nd[1]) * d == n * int(dd[0]):
     yield n,d
   if nd[1] == dd[0] and int(nd[0]) * d == n * int(dd[1]):
     yield n,d

(n,d)=reduce(lambda (a,b),(d,c): (a*d,b*c), same(), (1,1))
print d/utils.gcd(n,d)
Exemplo n.º 51
0
# generate our pitches
anchor_pitches = [rr(-12, 12) for _ in range(5)]
pitch_range = (-24, 18)
pc_anneal = a.annealer(temp_f=lambda t: 1 - t,
                       energy_f=pc_energy(choice(anchor_pitches),
                                          m.pitch_distance),
                       state_gen=pc_gen(choice(anchor_pitches),
                                        pitch_range[0],
                                        pitch_range[1]),
                       accept_p=a.basic_acceptance)

pcs = collect_pcs(pc_anneal, 60, 100, 10)
print("pitches collected")

# get our durations
gcd = u.gcd(60, len(pcs))
flat_pcs = [p for pc_b in pcs for p in pc_b]
bucket_durs = u.gen_equal_partitions(60, len(pcs))
pcs = u.partition_equally(gcd, flat_pcs)
pos_pcs = [[((pc % 12) + 1.0) / 24.0 for pc in pc_b]
           for pc_b in pcs]
durs = [[(ceil(pc * (dur / sum(pc_b))), 8) for pc in pc_b]
        for pc_b, dur in zip(pos_pcs, bucket_durs)]
print("durations generated")

# generate notes
notes_prime = [deepcopy(note)
               for pc_coll, dur_coll in zip(pcs, durs)
               for note in list(st.make_notes(pc_coll, dur_coll))]
notes = [u.multiply_by(choice([3]), n)
         if abs(random() - random()) < 0.2 and n.written_duration >= 0.125
Exemplo n.º 52
0
def fracs_in_range(n):
    count = 0
    for i in range(n//3+1,(n//2)+n%2):
        if gcd(i,n) == 1: count += 1
    return count
Exemplo n.º 53
0
#!/usr/bin/env python
from __future__ import division
from itertools import combinations
from utils import gcd

nrs = [(i, str(i)) for i in xrange(10, 100)]
pairs = ((0, 0), (0, 1), (1, 0), (1, 1))

pn = pd = 1

for (n, ns), (d, ds) in combinations(nrs, 2):
    if n < d:
        for i, j in pairs:
            if ds[1 - j] != '0' and ns[i] == ds[j] \
                    and int(ns[1 - i]) / int(ds[1 - j]) == n / d \
                    and ns[1] != '0':
                pn *= n
                pd *= d
                print '%d / %d == %s / %s' % (n, d, ns[1 - i], ds[1 - j])

g = gcd(pn, pd)
print 'product: %d / %d' % (pn/ g, pd / g)
print 'answer: %d' % (pd / g)
Exemplo n.º 54
0
from utils import gcd

N = 3/7.
L = 1000000
mina = N
for b in range(L, L-7, -1):
    a = N - int(b*N) * 1.0/b
    if mina > a != 0: mina, minD = a,b
 
print "Answer to PE71 =", int(minD*N), "/", minD

print gcd(56*7, 78*7)
goal = 3.0/7
print goal

m_num = 4
m_den = 1

cmin = 200

for num in range(421262, 430000):
    for den in range(989586, 1000000):
        res = 1.0*num/den
        if res <  goal:
            #print num, den, 1.0*num/den
            if goal - res < cmin:
                m_num = num
                m_den = den 
                cmin = goal - res
            break
print 'result:', m_num, m_den, 1.0*m_num/m_den      
Exemplo n.º 55
0
def outer_loop(params, x_f, filter_location, filter_estimation, simulation=None):
    permute = np.empty(params.total_loops)
    permute_b = np.empty(params.total_loops)
    x_samp = []

    # for i in xrange(params.total_loops):
    #     if i < params.location_loops:
    #         x_samp.append(np.zeros(params.B_location, dtype=np.complex128))
    #     else:
    #         x_samp.append(np.zeros(params.B_estimation, dtype=np.complex128))

    hits_found = 0
    hits = np.zeros(params.n)
    scores = np.zeros(params.n)

    # Inner loop
    for i in xrange(params.total_loops):
        a = 0
        b = 0

        # GCD test
        # http://en.wikipedia.org/wiki/GCD_test
        while utils.gcd(a, params.n) != 1:
            a = np.random.randint(params.n)
            # print 'check', a, params.n, utils.gcd(a, params.n)
        ai = utils.mod_inverse(a, params.n)

        permute[i] = ai
        permute_b[i] = b

        perform_location = i < params.location_loops

        if perform_location:
            current_filter = filter_location
            current_B = params.B_location
        else:
            current_filter = filter_estimation
            current_B = params.B_estimation

        inner_loop_locate_result = inner_loop_locate(
            x=x_f,
            n=params.n,
            filt=current_filter,
            B=current_B,
            B_threshold=params.B_threshold,
            a=a,
            ai=ai,
            b=b
        )

        x_samp.append(inner_loop_locate_result['x_samp'])
        # assert x_samp[i].shape == inner_loop_locate_result['x_samp'].shape
        # print i, x_samp[i].shape, inner_loop_locate_result['x_samp'].shape
        assert inner_loop_locate_result['J'].size == params.B_threshold

        if perform_location:
            inner_loop_filter_result = inner_loop_filter(
                J=inner_loop_locate_result['J'],
                B=current_B,
                B_threshold=params.B_threshold,
                loop_threshold=params.loop_threshold,
                n=params.n,
                a=a,
                hits_found=hits_found,
                hits=hits,
                scores=scores
            )

            hits_found = inner_loop_filter_result['hits_found']
            hits = inner_loop_filter_result['hits']
            scores = inner_loop_filter_result['scores']

        # print params.B_threshold, inner_loop_locate_result['J'][0], inner_loop_locate_result['J'][1], hits_found

    print('Number of candidates: {0}'.format(hits_found))

    # Estimate values
    answers = estimate_values(
        hits=hits,
        hits_found=hits_found,
        x_samp=x_samp,
        loops=params.total_loops,
        n=params.n,
        permute=permute,
        B_location=params.B_location,
        B_estimation=params.B_estimation,
        filter_location=filter_location,
        filter_estimation=filter_estimation,
        location_loops=params.location_loops
    )

    # Reconstructed signal
    x_f = np.zeros(params.n)
    for location, value in answers.iteritems():
        print 'got', int(location), np.abs(value)
        x_f[int(location)] = np.abs(value)

    # Counts
    xc = np.zeros(params.n)
    for i in xrange(params.n):
        xc[i] = scores[i] * 1./ params.total_loops

    # debug
    if simulation is not None:
        fig = plt.figure()
        ax = fig.gca()
        ax.plot(
            simulation.t, xc, '-x',
            simulation.t, simulation.x_f * params.n, '-x',
            simulation.t, x_f * params.n, '-.x',
        )
        ax.legend(
            (
                'counts',
                'true signal',
                'reconstruction'
            )
        )
        ax.set_xlim(right=simulation.t.shape[-1]-1)

    return {
        'x_f': x_f,
        'answers': answers
    }
Exemplo n.º 56
0
def test_gcd_correctness():
    assert_equal(utils.gcd(976, 1024), 16)
    assert_equal(utils.gcd(125, 1024), 1)
    assert_equal(utils.gcd(380, 1024), 4)
Exemplo n.º 57
0
Arquivo: p71.py Projeto: icot/euler
def coprimes(n):
    return [k for k in xrange(2, (n/2) +1) if gcd(k, n) == 1]