Skip to content
scipython.com

P5.1.2The IPython %%timeit magic: highly composite numbers

Using the fastest algorithm from the previous question, devise a short piece of code to determine the highly composite numbers less than 100000 and use the %%timeit cell magic to time its execution. A highly composite number is a positive integer with more factors than any smaller positive integer, for example: \(1, 2, 4, 6, 12, 24, 36, 48, \cdots\).

Show solution

Here is one solution:

In [x]: %%timeit
   ...: nmax = 100000
   ...: nfmax = 0
   ...: hcn = []
   ...: for n in range(1,nmax+1):
   ...:     nfacs = len(factors2(n))
   ...:     if nfacs > nfmax:
   ...:         hcn.append((n, nfacs))
   ...:         nfmax = nfacs
   ...:
1 loops, best of 3: 2.44 s per loop

Note that the variable hcn is not available outside of the %%timeit cell: to find out what the highly composite numbers less than 100000 actually are it is necessary to rerun the code inside this block without the %%timeit magic directive.