Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import itertools
- from math import sqrt
- import time
- import random
- def generateTriples( lim, a = 3, b = 4, c = 5 ):
- h = max( a, b, c )
- if h > lim:
- return
- i = 1
- while i * h <= lim:
- yield ( a * i, b * i, c * i )
- i += 1
- for x in generateTriples(lim, a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c):
- yield x
- for x in generateTriples(lim, a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c):
- yield x
- for x in generateTriples(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c):
- yield x
- def countTriplesFrom( n ):
- s = set( c * c for c in n )
- count = 0
- for ( a, b ) in itertools.combinations( n, 2 ):
- c = a * a + b * b
- if c in s:
- #print ( a, b, sqrt( c ) )
- count += 1
- return count
- def countTriplesFrom_fast( n ):
- s = set( n )
- l = max( n )
- count = 0
- for ( a, b, c ) in generateTriples( l ):
- if ( a in s ) and ( b in s ) and ( c in s ):
- #print ( a, b, c )
- count += 1
- return count
- def trial( f, n, numTrials ):
- start = time.clock()
- for t in xrange( numTrials ):
- f( n )
- end = time.clock()
- return ( end - start ) * 1.0 / numTrials
- L = 2000000
- N = 6000
- X = random.sample( xrange( 1, L + 1 ), N )
- T = 3
- from sys import setrecursionlimit
- setrecursionlimit(2000)
- print "L=",L,"N=",N
- print "O(N^2)", trial( countTriplesFrom, X, T )
- print "O(L log L)", trial( countTriplesFrom_fast, X, T )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement