# Useful Functions

``````

In [1]:

def primes_upto(n):
"""
Generator for primes up to n.
For primes under 'n', just use n-1.
"""
if n < 2:
return
marked = [0] * (n+1);
value = 3
yield 2
while value <= n:
if marked[value] == 0:
yield value
i = value
while i <= n:
marked[i] = 1
i += value
value += 2

list(primes_upto(20))

``````
``````

Out[1]:

[2, 3, 5, 7, 11, 13, 17, 19]

``````
``````

In [2]:

def num_digits(n, base=10):
"""
Number of digits for the number 'n' given some 'base'.
"""
if n < 0:
return num_digits(-n, base)
if n < base:
return 1
return 1 + num_digits(n//base, base)

for b in [2, 8, 10, 16]:
print("255 in base %d has %d digits."%(b, num_digits(255, b)))

``````
``````

255 in base 2 has 8 digits.
255 in base 8 has 3 digits.
255 in base 10 has 3 digits.
255 in base 16 has 2 digits.

``````
``````

In [3]:

import itertools

print('Permutations:', list(itertools.permutations([1,2,3])))

``````
``````

Permutations: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

``````
``````

In [2]:

import math
def is_pentagonal(x):
# See test for pentagonal numbers
# https://en.wikipedia.org/wiki/Pentagonal_number
n = math.sqrt(24 * x + 1) + 1
return n/6 == n//6

``````
``````

In [3]:

import math
def is_hexagonal(x):
# See test for pentagonal numbers
# https://en.wikipedia.org/wiki/Hexagonal_number
n = math.sqrt(8 * x + 1) + 1
return n/4 == n//4

``````
``````

In [ ]:

``````