Пример #1
0
# Find the number of lengths of wire below 2 000 000
# that can form a right-angled triangle in exactly one way

from useful import gcd
		
oneWay = {}

n = 1
m = 2
while m*m + 2*m*n + m*m <= 2000000 :
	val = 2*m*(m+n)
	while val <= 2000000 :
		if gcd(m,n) == 1 :
			count = 1
			while count*val <= 2000000 :
				if count*val in oneWay :
					oneWay[count*val] = False
				else :
					oneWay[count*val] = True
				count += 1
		m += 2
		val = 2*m*(m+n)
	n += 1
	m = n+1

print len([key for key in oneWay.keys() if oneWay[key] == True])
Пример #2
0
max_N = 0

for N in xrange(1, 1001) :
  root = sqrt(N)
  floor_root = int(root)
  if floor_root * floor_root == N :
    # Perfect square
    continue
  left_of_frac, frac_top, frac_bottom = floor_root, 1, floor_root
  lis = []

  print N
  while True :
    lis.append(left_of_frac)
    new_frac_bottom_before_reduce = N - frac_bottom*frac_bottom
    divisor = gcd(frac_top, new_frac_bottom_before_reduce)
    new_frac_top_int_part = new_frac_bottom_before_reduce / divisor
    assert(frac_top == divisor)
    new_frac_top_before_reduce = (sqrt(N) + frac_bottom)
    new_left_of_frac = int(new_frac_top_before_reduce / new_frac_top_int_part)
    new_frac_top = (new_frac_top_before_reduce -
      new_left_of_frac * (new_frac_top_int_part))
    new_frac_bottom = int(sqrt(N) - new_frac_top + 0.0001)
    left_of_frac, frac_top, frac_bottom = (new_left_of_frac,
      new_frac_top_int_part, new_frac_bottom)

    # Update the convergent fraction
    x, y = 1, 0
    for left_term in reversed(lis) :
      y, x = x, y
      x, y = left_term * y + 1 * x, y
Пример #3
0
def fracreduce((p1, q1)) :
  d = gcd(p1,q1)
  return (p1/d, q1/d)
Пример #4
0
# In a sorted list of all reduced proper fractions where the denominator <= 1000000,
# find the fraction to the left of 3/7

from useful import gcd

lowest = (2,7)

for denom in range(2,1000001) :
	if denom == 7:
		continue
	x = 3 * denom / 7
	while (x+1)*7 < 3*denom :
		x += 1
	if gcd(x,denom) != 1 :
		continue
	if lowest[1] * x > lowest[0] * denom :
		lowest = (x,denom)

print lowest
Пример #5
0
# This program does not terminate in a timely fashion, because we use a 
# very generous upper bound for m, but it does output the solution within
# 1 minute

from math import sqrt
from useful import gcd

top = 100 * 1000 * 1000

count = 0
for m in xrange(top) :
  if m % 2 == 1 :
    lower = 2
  else :
    lower = 1
  for n in xrange(lower, m, 2) :
    if gcd(m, n) != 1 :
      continue
    x = m*m - n*n
    y = 2*m*n
    z = m*m + n*n

    if z % (x-y) == 0 :
      # For what scaling values of k is k * (x + y + z) < 100 million?
      k = top / (x+y+z)
      count += k
      print (x,y,z), k, count

print count