Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Solved problem75

  • Loading branch information...
commit 061e659cfbfdade3dc29b0d9111c9256c720886b 1 parent d352114
Charles Leifer authored May 11, 2012

Showing 1 changed file with 68 additions and 0 deletions. Show diff stats Hide diff stats

  1. 68  problem75.py
68  problem75.py
... ...
@@ -0,0 +1,68 @@
  1
+#!/usr/bin/env python
  2
+import math
  3
+
  4
+"""
  5
+had to do a little wikipedia dive for this one, looked at generating primitive
  6
+pythagorean triples.  found euclid's formula:
  7
+
  8
+http://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
  9
+
  10
+m and n, such that m > n, m+n is odd, and m and n are coprime
  11
+
  12
+a = m*m - n*n
  13
+b = 2mn
  14
+c = m*m + n*n
  15
+
  16
+also we know that:
  17
+a + b + c <= 1500000
  18
+
  19
+from the formula:
  20
+c = m*m + n*n
  21
+
  22
+maximum value for c is 1499997 (a < b < c, 1 < 2 < 1499997) so we can
  23
+figure out a good upper bound for m:
  24
+
  25
+c < 2(m*m)
  26
+1499997 < 2(m*m)
  27
+sqrt(1499997/2) < m
  28
+"""
  29
+L = 1500000
  30
+max_c = L - 3
  31
+max_m = int(math.sqrt(max_c / 2)) + 1
  32
+is_odd = lambda s: s % 2 == 1
  33
+
  34
+def memo(fn):
  35
+    _memo = {}
  36
+    def inner(n):
  37
+        if n not in _memo:
  38
+            _memo[n] = fn(n)
  39
+        return _memo[n]
  40
+    return inner
  41
+
  42
+@memo
  43
+def divisors(n):
  44
+    d = set()
  45
+    for s in range(1, int(math.sqrt(n)) + 1):
  46
+        if n % s == 0:
  47
+            d.add(s)
  48
+            d.add(n/s)
  49
+    return d
  50
+
  51
+coprime = lambda m, n: divisors(m) & divisors(n) == set([1])
  52
+counts = {}
  53
+
  54
+for m in range(2, max_m):
  55
+    for n in range(1, m):
  56
+        if is_odd(m+n) and coprime(m, n):
  57
+            a = (m*m) - (n*n)
  58
+            b = 2*m*n
  59
+            c = (m*m) + (n*n)
  60
+
  61
+            length = a + b + c
  62
+            
  63
+            while length < L:
  64
+                counts.setdefault(length, 0)
  65
+                counts[length] += 1
  66
+                length += (a+b+c)
  67
+
  68
+print sum([v for v in counts.values() if v == 1])

0 notes on commit 061e659

Please sign in to comment.
Something went wrong with that request. Please try again.