Skip to content

Instantly share code, notes, and snippets.

@thebecwar
Last active August 29, 2017 22:47
Show Gist options
  • Save thebecwar/bfb01826d4b4394c4466a6191fd71a56 to your computer and use it in GitHub Desktop.
Save thebecwar/bfb01826d4b4394c4466a6191fd71a56 to your computer and use it in GitHub Desktop.
Python script for calculating Triangle Square numbers
# This is Python 3, but the code should be pretty trivial to convert to Python 2
import time
start = time.time()
# Original method for calculating
a = 0
b = 0
x = []
h = 0
n = 0
y = []
while a < 1000000:
a = a + 1
b = b + a
x.append(b)
while h < 1000000:
n = h ** 2
h = h + 1
y.append(n)
c = list(set(x) & set(y))
c.sort()
print(c)
print('Original method took {} seconds'.format(time.time() - start))
start = time.time()
# Optimized method for calculating
def find_ts_numbers(lessThan):
ts_numbers = []
t_a = 0
t_b = 0
n = 1
next_square = n * n
while t_b <= lessThan:
t_a = t_a + 1
t_b = t_b + t_a
if t_b == next_square: # the number t_b is a triangle square number
ts_numbers.append(t_b)
n = n + 1
next_square = n * n
elif t_b > next_square: # we passed the square number
n = n + 1
next_square = n * n
return ts_numbers
numbers = find_ts_numbers(55420693057)
print(numbers)
print('Optimized method {} seconds'.format(time.time() - start))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment