Skip to content

Instantly share code, notes, and snippets.

@ajsharma
Last active December 14, 2015 03:39
Show Gist options
  • Save ajsharma/5022355 to your computer and use it in GitHub Desktop.
Save ajsharma/5022355 to your computer and use it in GitHub Desktop.
My solution to ZeroCater's February Mathy challenge.
class Primes:
"""Get primes, fast. Eat lots of memory"""
@staticmethod
def list_all_up_to(ceiling):
"""Creates a list of prime numbers up to the ceiling"""
limit = int((ceiling - 1) / 2)
prime_map = [True] * limit
list_of_primes = [2]
index = 0
prime = 3
# compose map of primes and composites up to sqrt of ceiling
while prime * prime < ceiling:
# print "I think " + str(prime) + " is prime"
if prime_map[index]:
list_of_primes.append(prime)
step = (2 * index * index) + (6 * index) + 3
while step < limit:
prime_map[step] = False
step += (2 * index) + 3
index += 1
prime += 2
# translate remaining map into list
while index < limit:
if prime_map[index]:
# print "I think " + str(prime) + " is prime"
list_of_primes.append(prime)
index += 1
prime += 2
return list_of_primes
class Chain:
"""Chains are the representation of a lists of numbers
the numbers themselves aren't important since we
only care if they sum of n-1 is clean and what the
length would be"""
__last_element = 0
__n_minus_one_sum = 0
__length = 0
def length(self):
return self.__length
def last_element(self):
return self.__last_element
def append(self, value):
self.__last_element = value
self.__n_minus_one_sum += value
self.__length += 1
def is_clean(self):
# print "Checking chain ending with: " + str(self.__last_element)
if self.__n_minus_one_sum % self.__last_element == 0:
print "Chain found ending with: " + str(self.__last_element)
return True
return False
# Runtime code
import datetime
# track duration
start_time = datetime.datetime.now()
# vars for storing solutions
number_of_chains_found = 0
chain_lengths = []
chain = Chain()
try:
for number in Primes.list_all_up_to(500000000):
chain.append(number)
if(chain.is_clean()):
number_of_chains_found += 1
chain_lengths.append(chain.length())
finally:
print str(number_of_chains_found) + " chains found"
print "Lengths of chains: " + str(chain_lengths)
end_time = datetime.datetime.now()
print (end_time - start_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment