CS 61A

Structure and Interpretation of Computer Programs, Spring 2015

Instructor: John DeNero




Question | Less Than Counters

Write the function countfactors, then the function countprimes. Can you generalize the logic of the counting computation?

def count_factors(n):
    """
    Return the number of positive factors n or smaller
    >>> count_factors(2)
    2
    >>> count_factors(4) 
    3
    >>> count_factors(12)
    6
    """
    ## YOUR CODE HERE ##

def count_primes(n):
    """
    Return the number of primes n or smaller
    >>> count_primes(2)
    1
    >>> count_primes(3)
    2
    >>> count_primes(4)
    2
    >>> count_primes(5)
    3
    >>> count_primes(10)
    4
    >>> count_primes(20)
    8
    >>> count_primes(30)
    10
    """
    ## YOUR CODE HERE ##

def count_cond(condition):
    """
    Return a one-argument function that counts
    the numbers less than that argument that 
    fulfills the condition
    """
    ## YOUR CODE HERE ##

count_primes_new = count_cond(___________)
count_factors_new = count_cond(___________)
def is_prime(n):
    if n < 2:
        return False
    i = 2
    while i < n:
        if n % i == 0:
            return False
        i += 1
    return True

# count_factors and count_primes should look
# something like this 
def count_cond(condition):
    def counter(n):
        i, count = 1, 0
        while i <= n:
            if condition(n, i):
                count += 1
            i += 1
        return count
    return counter

count_primes_new = count_cond(lambda n, i: is_prime(i))
count_factors_new = count_cond(lambda n, i: n % i == 0)