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]:
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)))
In [3]:
import itertools
print('Permutations:', list(itertools.permutations([1,2,3])))
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 [ ]: