Beispiel #1
0
def run():
    lower_n, lower_d = 0, 1
    upper_n, upper_d = 3, 7
    i, n, d = 1000000, 0, 0
    while i > 0:
        new_n = upper_n * i // upper_d
        gcd = euler.gcd(new_n, i)
        new_lower_n, new_lower_d = new_n // gcd, i // gcd
        if new_lower_n * lower_d > new_lower_d * lower_n:
            if new_lower_n * upper_d < new_lower_d * upper_n:
                lower_n, lower_d = new_lower_n, new_lower_d
                n = new_n
                d = i
        i -= 1
    return n // euler.gcd(n, d)
Beispiel #2
0
def euler33():
    nominators = 1
    denominators = 1
    for a in range(10, 100):
        for b in range(a + 1, 100):
            if a % 10 == 0 and b % 10 == 0:
                continue
            value = Decimal(a) / Decimal(b)
            a_str = str(a)
            b_str = str(b)
            a0 = int(a_str[0])
            b0 = int(b_str[0])
            a1 = int(a_str[1])
            b1 = int(b_str[1])
            if b0 == 0 or b1 == 0:
                continue
            if Decimal(a0) / Decimal(b0) == value and a1 == b1:
                nominators *= a
                denominators *= b
            if Decimal(a0) / Decimal(b1) == value and a1 == b0:
                nominators *= a
                denominators *= b
            if Decimal(a1) / Decimal(b0) == value and a0 == b1:
                nominators *= a
                denominators *= b
            if Decimal(a1) / Decimal(b1) == value and a0 == b0:
                nominators *= a
                denominators *= b

    denominators //= gcd(nominators, denominators)
    print(denominators)
Beispiel #3
0
def intTests( lines ):
    for i in xrange(len(lines)):
        if i % 10 ==0: print i
        for j in xrange(i):
            if i == j:
                continue
            (x1,y1),(x2,y2) = tuple(lines[i])
            (u1,v1),(u2,v2) = tuple(lines[j])
            dx = x2 - x1
            dy = y2 - y1
            du = u2 - u1
            dv = v2 - v1
            if euler.gcd(dx,du) == euler.gcd(dy,dv):
                print 'parallel',dx,du
                continue                
            else:
                pass
Beispiel #4
0
def solveb(n):
    cnt = 0
    for item in orcharditer(n):
        div = euler.gcd(item[0], item[1])
        if div > 1 and max(item[0], item[1]) > 0:
            #print item, div
            sumitem = (item[0] / div + item[1] / div)
            if sumitem % 2 == 0:
                cnt += 1
    return cnt * 6 + 6 * n
Beispiel #5
0
def solveb( n ):
    cnt = 0
    for item in orcharditer(n):
        div = euler.gcd(item[0],item[1])
        if div > 1 and max(item[0],item[1])>0:
            #print item, div
            sumitem = (item[0]/div + item[1]/div)
            if sumitem%2 == 0:
                cnt += 1
    return cnt*6 + 6*n
Beispiel #6
0
def h(n):
    cnt = 0
    for x, y in orcharditer(n):  #alt_iter(n):
        gcd = euler.gcd(x, y)
        if gcd > 1:
            xd = x / gcd
            yd = y / gcd
            if (xd + yd) % 2 == 0:
                cnt += 1
    return (cnt + n - 1) * 6
Beispiel #7
0
def h(n):
    cnt = 0
    for x, y in orcharditer(n):#alt_iter(n):
        gcd = euler.gcd(x, y)
        if gcd > 1:
            xd = x / gcd
            yd = y / gcd
            if (xd + yd) % 2 == 0:
                cnt += 1
    return (cnt + n -1) * 6
Beispiel #8
0
def countReduced(b, x, y):
    # Counts reduced fractions x < a / b < y
    x0 = min(x, y)
    y0 = max(x, y)
    assert (x0 <= y0)

    count = 0
    for a in range(1 + int(b * x), int(math.ceil(b * y) + 0.5)):
        if gcd(a, b) == 1:
            count += 1
    return count
Beispiel #9
0
def genPythagorianTriplesWithPerimeter(p):
    """ returns all pythagorian triples up to perimeter (a + b + c) p """
    for m in range(1, int(math.sqrt((p // 2 + 1))) + 1):
        for n in range(1, min(int(p // (2 * m)) + 1 - m, m)):
            if ((m - n) % 2 == 1):
                if (gcd(m, n) == 1):
                    a , b = min(m * m - n * n, 2 * m * n) , max(m * m - n * n, 2 * m * n)
                    c = m * m + n * n

                    if (p % (a + b + c) == 0):
                        k = (p // (a + b + c))
                        return (a * b * c * (k ** 3))
Beispiel #10
0
def getTrueIntersectionPoint(l1, l2):
    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]
    
    dx = (l1[0][0] - l1[1][0], l2[0][0] - l2[1][0])
    dy = (l1[0][1] - l1[1][1], l2[0][1] - l2[1][1])

    div = det(dx, dy)
    
    if (div == 0):
       return None

    d = (det(*l1), det(*l2))
    x = det(d, dx), div
    g = gcd(x[0],x[1])
    x = x[0] // g, x[1] // g
    y = det(d, dy), div
    g = gcd(y[0],y[1])
    y = y[0] // g, y[1] // g
    if (div < 0):
        x = -x[0],-x[1]
        y = -y[0],-y[1]

    xf = x[0] / x[1]
    if xf < max(min(l1[0][0], l1[1][0]), min(l2[0][0], l2[1][0])) or \
       xf > min(max(l1[0][0], l1[1][0]), max(l2[0][0], l2[1][0])):
               return None

    yf = y[0] / y[1]
    if yf < max(min(l1[0][1], l1[1][1]), min(l2[0][1], l2[1][1])) or \
       yf > min(max(l1[0][1], l1[1][1]), max(l2[0][1], l2[1][1])):
               return None

    if (xf == l1[0][0] and yf == l1[0][1]) or \
       (xf == l1[1][0] and yf == l1[1][1]) or \
       (xf == l2[0][0] and yf == l2[0][1]) or \
       (xf == l2[1][0] and yf == l2[1][1]):
        return None
    
    return x, y
Beispiel #11
0
def unconcealed(p, q, e):
    """Naive solution (too slow)
    """
    n   = p * q
    phi = (p-1)*(q-1)
    assert euler.gcd(e, phi) == 1
    assert e > 1
    assert e < phi

    cnt = 0
    for m in xrange(n):
        c = (m**e) % n
        if c == m:
            cnt += 1
    return cnt
Beispiel #12
0
def naive_totient(x):
    if x == 1: return 1
    return sum(1 for k in range(1,x) if gcd(x,k) == 1)
Beispiel #13
0
def is_same_ratio((a, b, c)):
    x = e.gcd(a, b)
    y = e.gcd(b, c)
    return (b / x == c / y and a / x == b / y)
Beispiel #14
0
from euler import gcd

print gcd(461952, 116298)
Beispiel #15
0
# https://projecteuler.net/problem=73
from euler import gcd
from math import ceil
from time import time
T = time()

lower_bound = 1/3
upper_bound = 1/2
count = 0
numerator_of_result = 0
limit = 12000

for d in range(1, limit+1):
    n = ceil(d*lower_bound)
    fraction = n/d

    while fraction < upper_bound:
        if gcd(n, d) == 1:
            if lower_bound < fraction < upper_bound:
                # print(n, d)
                count += 1

        n += 1
        fraction = n/d

print(count)
print("time elapsed:", time() - T)
Beispiel #16
0
# -*- coding:utf-8 -*-
"""Project Euler problem 129"""

from euler import gcd

def R(k):
    return int("1"*k)

def A(n):
    k=len(str(n))
    mod = R(k)%n
    while mod!=0:
        mod = (10*mod+1)%n
        k+=1
    return k

n = 1000000
while True:
    if gcd(n, 10)==1:
        if A(n)>1000000:
            break
    n += 1
print("Answer: " + str(n))
Beispiel #17
0
def f(d):
    return sum(1 if 2 * x < d < 3 * x and gcd(x, d) == 1 else 0
               for x in xrange(d // 3, d // 2 + 1))
Beispiel #18
0
#!/usr/bin/python

from euler import gcd
import math

UPPER = 12000

assert (int(-3.2) == -3)

assert (gcd(32, 12) == 4)
assert (gcd(32, 11) == 1)


def countReduced(b, x, y):
    # Counts reduced fractions x < a / b < y
    x0 = min(x, y)
    y0 = max(x, y)
    assert (x0 <= y0)

    count = 0
    for a in range(1 + int(b * x), int(math.ceil(b * y) + 0.5)):
        if gcd(a, b) == 1:
            count += 1
    return count


assert (countReduced(8, 1 / 3, 1 / 2) == 1)
assert (countReduced(5, 1 / 3, 1 / 2) == 1)
assert (countReduced(7, 1 / 3, 1 / 2) == 1)
assert (countReduced(4, 1 / 3, 1 / 2) == 0)
Beispiel #19
0
def f(d):
    return sum(1 if 2*x < d < 3*x and gcd(x, d)==1 else 0
        for x in xrange(d//3, d//2+1))
	def simplify(self):
		gcd = euler.gcd(self.numerator,self.denominator)
		return Fraction(self.numerator/gcd,self.denominator/gcd)
Beispiel #21
0
 def testGCD3(self):
     self.assert_( euler.gcd(3,7) == 1 )
Beispiel #22
0
def is_same_ratio((a, b, c)):
  x = e.gcd(a, b)
  y = e.gcd(b, c)
  return (b/x == c/y and a/x == b/y)
Beispiel #23
0
from numpy import prod
from euler import gcd

nums = list()
dens = list()

for i in range(1, 10):
    for j in range(1, 10):
        for k in range(i, 10):
            for l in range(1, 10):
                a = 10 * i + j
                b = 10 * k + l
                frac = a / b
                if (i != k and j != l and ((frac == i / k and j == l) or
                                           (frac == i / l and j == k) or
                                           (frac == j / k and i == l) or
                                           (frac == j / l and i == k))):
                    #print("{}{}/{}{}".format(i, j, k, l))
                    nums.append(a)
                    dens.append(b)

num = prod(nums)
den = prod(dens)
print(den / gcd(num, den))
Beispiel #24
0
 def test_gcd2(self):
     r = gcd(461952, 116298)
     self.assertEqual(18, r)
Beispiel #25
0
 def test_gcd(self):
     r = gcd(9, 4)
     self.assertEqual(1, r)
Beispiel #26
0
z , m = 1 , 1
for a in range(11,100): 
	if a % 10:
		for b in range(11 , a): 
			if b % 10:
				a0 , a1 = divmod(a , 10)
				b0 , b1 = divmod(b , 10)
				if (a1 == b0 and b * a0 == a * b1) or (a0 == b1 and b * a1 == a * b0):
					z *= b
					m *= a
from euler import gcd
print m / gcd(z , m)
Beispiel #27
0
def fast_unconcealed(p, q, e):
    # From the "Handbook of applied cryptography", which is on google
    # books p. 290
    a = (1+euler.gcd(e-1, p-1))
    b = (1+euler.gcd(e-1, q-1))
    return a*b
Beispiel #28
0
import euler
import sympy

def fastA(p):
    # from http://mathlesstraveled.com/2011/11/17/fun-with-repunit-divisors-more-solutions/
    i = 1
    x = 1
    while 1:
        x = (10*x +1) % p
        i += 1
        if x == 0:
            break
    return i

import itertools

lst = []
for i in itertools.count(start = 6):
#for i in xrange(6, 10000):
    if sympy.isprime(i):
        continue
    if euler.gcd(i, 10) != 1:
        continue
    if (i-1)%fastA(i) == 0:
        lst.append(i)
    if len(lst) == 25:
        break
print sum(lst)
Beispiel #29
0
 def testGCD2(self):
     self.assert_( euler.gcd(18,12) == 6 )
Beispiel #30
0
#!/usr/bin/python
# coding: UTF-8
"""
@author: CaiKnife

Smallest multiple
Problem 5
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""

from euler import gcd

answer = 1
for i in range(1, 21):
    answer *= i / gcd(answer, i)

print answer
Beispiel #31
0
 def testGCD1(self):
     self.assert_( euler.gcd(12,24) == 12 )
Beispiel #32
0
# -*- coding:utf-8 -*-
"""Project Euler problem 129"""

from euler import gcd


def R(k):
    return int("1" * k)


def A(n):
    k = len(str(n))
    mod = R(k) % n
    while mod != 0:
        mod = (10 * mod + 1) % n
        k += 1
    return k


n = 1000000
while True:
    if gcd(n, 10) == 1:
        if A(n) > 1000000:
            break
    n += 1
print("Answer: " + str(n))
Beispiel #33
0
from itertools import product
from euler import gcd

result = []

for d1, d2 in product(xrange(1, 10), xrange(1, 10)):
	denominator = d1 * 10 + d2
	for n1, n2 in product(xrange(1, d1+1), xrange(1, 10)):
		numerator = n1 * 10 + n2
		if numerator >= denominator:
			break
		fraction_result = float(numerator) / float(denominator)
		numerator_digits = [n1, n2]
		denominator_digits = [d1, d2]
		common_digits_iter = (digit for digit in numerator_digits if digit in denominator_digits)
		for common_d in common_digits_iter:
			numerator_digits.remove(common_d)
			denominator_digits.remove(common_d)
			tmp_num = numerator_digits[0]
			tmp_den = denominator_digits[0]
			if float(tmp_num) / float(tmp_den) == fraction_result:
				result.append((tmp_num, tmp_den))
			break
		
numerator, denominator = reduce(lambda (n1, d1), (n2, d2): (n1 * n2, d1 * d2), result)
print denominator / gcd(numerator, denominator)
Beispiel #34
0

def R(k):
    return (10 ** k - 1) / 9


def A(n):
    for k in xrange(2, n + 2):
        if R(k) % n == 0:
            return k
    assert 1 == 0


def fastA(p):
    # from http://mathlesstraveled.com/2011/11/17/fun-with-repunit-divisors-more-solutions/
    i = 1
    x = 1
    while 1:
        x = (10 * x + 1) % p
        i += 1
        if x == 0:
            break
    return i


# this is a key to this - k > n (but probably not by much)
for i in xrange(10 ** 6, 10 ** 7):
    if euler.gcd(i, 10) == 1:
        if fastA(i) > 10 ** 6:
            print i
Beispiel #35
0

def R(k):
    return (10**k - 1) / 9


def A(n):
    for k in xrange(2, n + 2):
        if R(k) % n == 0:
            return k
    assert (1 == 0)


def fastA(p):
    # from http://mathlesstraveled.com/2011/11/17/fun-with-repunit-divisors-more-solutions/
    i = 1
    x = 1
    while 1:
        x = (10 * x + 1) % p
        i += 1
        if x == 0:
            break
    return i


# this is a key to this - k > n (but probably not by much)
for i in xrange(10**6, 10**7):
    if euler.gcd(i, 10) == 1:
        if fastA(i) > 10**6:
            print i
Beispiel #36
0
#!/usr/bin/python
from math import sqrt
import sys
from numpy import array, dot
from euler import gcd

stop = 1500000
triangles = {}

for m in xrange(2, int(sqrt(stop / 2)) + 1):
    for n in xrange(1, m + 1):
        if (n + m) % 2 == 1 and gcd(n, m) == 1:
            a = m*m + n*n
            b = m*m - n*n
            c = 2*m*n
            p = a+b+c
            while p <= stop:
                triangles[p] = triangles.setdefault(p, 0) + 1
                p += a + b + c

print len([x for x in triangles.itervalues() if x == 1])

sys.exit(0)

# see
# http://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples

A = array([1, -2, 2, 2, -1, 2, 2, -2, 3])
B = array([1, 2, 2, 2, 1, 2, 2, 2, 3])
C = array([-1, 2, 2, -2, 1, 2, -2, 2, 3])
A.shape = B.shape = C.shape = (3,3)
Beispiel #37
0
#!/usr/bin/env python

from euler import gcd

n = 50
t = 0

for i in xrange(1, n + 1):
    for j in xrange(1, n):
        m = gcd(i, j)
        t += min(i * m / j, m * (n - j) / i)

print t * 2 + n * n * 3
Beispiel #38
0
There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator.

If the product of these four fractions is given in its lowest common terms, find the value of the denominator.
"""
from euler import gcd

nontrivial_curious_fractions = []
for numerator in range(10, 100):
    for denominator in range(numerator + 1, 100):
        assert numerator / denominator < 1
        s = set(str(numerator)) & set(str(denominator)) - {'0'}
        if len(s) == 1:
            d = s.pop()
            try:
                numerator_, denominator_ = int(str(numerator).strip(d)), int(
                    str(denominator).strip(d))
            except ValueError:
                # int('') called due to double digit coincidence
                continue
            if numerator * denominator_ == numerator_ * denominator:
                nontrivial_curious_fractions.append((numerator, denominator))

assert len(nontrivial_curious_fractions) == 4
prod_numerators = prod_denominators = 1

for n, d in nontrivial_curious_fractions:
    prod_numerators *= n
    prod_denominators *= d

result = prod_denominators // gcd(prod_numerators, prod_denominators)
Beispiel #39
0
# https://projecteuler.net/problem=71
from euler import gcd
from math import floor
from time import time
T = time()

target = 3/7
result = 0
numerator_of_result = 0
limit = 10**6

for d in range(1, limit+1):
    numerator = floor(d*target)
    not_found = True

    while not_found:
        if gcd(numerator, d) == 1:
            not_found = False
        else:
            numerator -= 1

    fraction = numerator/d
    if result < fraction < target:
        result = fraction
        numerator_of_result = numerator

print(numerator_of_result)
print("time elapsed:", time() - T)
Beispiel #40
0
from euler import gcd
from time import time
T = time()

limit = 1500000
m = 2
wirelengths = []

limit_reached = False
while not limit_reached:
    if m % 2 == 0:
        start = 1
    else:
        start = 2
    for n in range(start, m, 2):
        if gcd(m, n) == 1:
            k = 1
            L_primitive = 2*m*(m+n)
            L = k*L_primitive

            if L > limit and n == start:
                limit_reached = True

            while L <= limit:
                wirelengths.append(L)
                k += 1
                L = k*L_primitive

    m += 1

once = set()
Beispiel #41
0
from euler import primes, gcd, radical

N = 120000
ps = primes(N)

rad = [0] + [radical(n, ps) for n in range(1, N+1)]
ans = 0
relradsorted = sorted(list(range(1, N)),key=lambda x: rad[x]/x)
radsorted    = sorted(list(range(1, N)),key=lambda x: rad[x])
m = 1000
for c in relradsorted:
    if rad[c]/c > 1/2:
        break
    for a in radsorted:
        if a > c//2-1:
            continue
        if rad[a] > (c/rad[c]):
            break
        b = c - a
        if gcd(a,b) == gcd(a,c) == gcd(b,c) == 1:
            if rad[a]*rad[b]*rad[c] < c:
                ans += c
print(ans)
Beispiel #42
0
def find_es(phi):
    return (e for e in xrange(2, phi) if euler.gcd(e, phi) == 1)
Beispiel #43
0
	if istr[1] == jstr[1]:
		return (int(istr[0]), int(jstr[0]))

	return (i, j)

num = 1
denom = 1

for i in range(11, 100):

	for j in range(11, 100):

		if i%10 == 0 and j%10 == 0:
			continue

		gcd = euler.gcd(i,j)

		if gcd == 1: continue

		a = i / gcd
		b = j / gcd

		x, y = simplify(i, j)

		# no cancellations
		if x == i and y == j: continue

		gcd = euler.gcd(x, y)
		x = x / gcd
		y = y / gcd
Beispiel #44
0
def resiliance(d):
    return sum(euler.gcd(i, d) == 1 for i in xrange(1, d))
Beispiel #45
0
import euler
import sympy


def fastA(p):
    # from http://mathlesstraveled.com/2011/11/17/fun-with-repunit-divisors-more-solutions/
    i = 1
    x = 1
    while 1:
        x = (10 * x + 1) % p
        i += 1
        if x == 0:
            break
    return i


import itertools

lst = []
for i in itertools.count(start=6):
    #for i in xrange(6, 10000):
    if sympy.isprime(i):
        continue
    if euler.gcd(i, 10) != 1:
        continue
    if (i - 1) % fastA(i) == 0:
        lst.append(i)
    if len(lst) == 25:
        break
print sum(lst)