Advertisement
markgritter

Finding Pythagorean triples

May 4th, 2013
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. import itertools
  2. from math import sqrt
  3. import time
  4. import random
  5.  
  6. def generateTriples( lim, a = 3, b = 4, c = 5 ):
  7.     h = max( a, b, c )
  8.     if h > lim:
  9.         return
  10.     i = 1
  11.     while i * h <= lim:
  12.         yield ( a * i, b * i, c * i )
  13.         i += 1
  14.    
  15.     for x in generateTriples(lim,  a - 2*b + 2*c,  2*a - b + 2*c,  2*a - 2*b + 3*c):
  16.         yield x
  17.     for x in generateTriples(lim,  a + 2*b + 2*c,  2*a + b + 2*c,  2*a + 2*b + 3*c):
  18.         yield x
  19.     for x in generateTriples(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c):
  20.         yield x
  21.  
  22. def countTriplesFrom( n ):
  23.     s = set( c * c for c in n )
  24.     count = 0
  25.  
  26.     for ( a, b ) in itertools.combinations( n, 2 ):
  27.         c = a * a + b * b
  28.         if c in s:
  29.             #print ( a, b, sqrt( c ) )
  30.             count += 1
  31.     return count
  32.  
  33. def countTriplesFrom_fast( n ):
  34.     s = set( n )
  35.     l = max( n )
  36.     count = 0
  37.  
  38.     for ( a, b, c ) in generateTriples( l ):
  39.         if ( a in s ) and ( b in s ) and ( c in s ):
  40.             #print ( a, b, c )
  41.             count += 1
  42.            
  43.     return count
  44.  
  45. def trial( f, n, numTrials ):
  46.     start = time.clock()
  47.     for t in xrange( numTrials ):
  48.         f( n )
  49.     end = time.clock()
  50.     return ( end - start ) * 1.0 / numTrials
  51.  
  52. L = 2000000
  53. N = 6000
  54. X = random.sample( xrange( 1, L + 1 ), N )
  55. T = 3
  56.  
  57. from sys import setrecursionlimit
  58. setrecursionlimit(2000)
  59.  
  60. print "L=",L,"N=",N
  61. print "O(N^2)", trial( countTriplesFrom, X, T )
  62. print "O(L log L)", trial( countTriplesFrom_fast, X, T )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement