Advertisement
lackofcheese

HCTN finder

Mar 18th, 2012
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. def get_divisor_counts(start, length):
  2.     """ Returns the number of divisors of every number from start up to, but
  3.    not including, start+length.
  4.    Requires: start >= 2
  5.    """
  6.     divisor_counts = [2]*length
  7.     for d in xrange(2, (start+length-1)/2 + 1):
  8.         for i in xrange(max(d*2-start, -start%d), length, d):
  9.             divisor_counts[i] += 1
  10.     return divisor_counts
  11.  
  12. def highly_composite_triangular_numbers():
  13.     """ An infinite generator which outputs all highly composite triangular
  14.    numbers, starting at T_1=1.
  15.    """
  16.     start = 0
  17.     divisor_counts = [0, 1, 2, 2, 3, 2] #Divisor counts
  18.     length = 6
  19.     nd_max = 0 #Maximum number of divisors seen so far
  20.     i = 1 #Current position in the array of divisor counts.
  21.     while True:
  22.         if i+1 >= length:
  23.             start += length-1
  24.             length *= 2
  25.             divisor_counts = get_divisor_counts(start, length)
  26.             i = 0
  27.         n = (i+start)*(i+start+1)
  28.         c = (n & -n).bit_length() #(largest power of 2 dividing n)+1
  29.         nd = divisor_counts[i]*divisor_counts[i+1]*(c-1)/c
  30.         if nd > nd_max:
  31.             yield i+start, n/2, nd
  32.             nd_max = nd
  33.         i += 1
  34.  
  35. def find_hctn(req=5000):
  36.     for i, n, nd in highly_composite_triangular_numbers():
  37.         if nd > req:
  38.             return i, n, nd
  39.  
  40. if __name__ == '__main__':
  41.     import time
  42.     start = time.clock()
  43.     count = 1
  44.     for i, n, nd in highly_composite_triangular_numbers():
  45.         print '({:02}) With {:5} divisors, T_i={:15} (i={:8}) [{:7.3f}s]'.format(
  46.             count, nd, n, i, time.clock()-start)
  47.         count += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement