CMU 15-112: Fundamentals of Programming and Computer Science
Writing-Session2 Practice

  1. digitCount(n)
    Write the function digitCount(n) that takes a possibly-negative int and returns the number of digits in it. So, digitCount(12323) returns 5, digitCount(0) returns 1, and digitCount(-111) returns 3. One way you could do this would be to return len(str(abs(n))), but you cannot do that, since you may not use strings here! This can be solved with logarithms, but seeing as this is the "loops unit", you should instead simply repeatedly remove the ones digit until you cannot.

  2. gcd(m, n)
    [Note: to receive any credit, you must solve this problem using Euclid's algorithm, and by no other means. In particular, do not just loop through all integers less than min(m,n) and find the common factors that way -- it is much too slow! Also, do not use math.gcd!]
    According to Euclid, the greatest common divisor, or gcd, can be found like so:
       gcd(x,y) == gcd(y, x%y)
    We can use that to quickly find gcd's. For example:
        gcd(270,250) == gcd(250, 20) # 270 % 250 == 20
                     == gcd(20, 10) # 250 % 20 == 10
                     == gcd(10, 0) # 20 % 10 == 0

    When we get to gcd(x,0), the answer is x. So gcd(270, 250) is 10. With this in mind, write the function gcd(x,y) that takes two positive integers x and y and returns their gcd using Euclid's gcd algorithm.

  3. hasConsecutiveDigits(n)
    Write the function hasConsecutiveDigits(n) that takes a possibly- negative int value n and returns True if that number contains two consecutive digits that are the same, and False otherwise.

  4. nthPrime(n) with fasterIsPrime(n) and
    Write the function nthPrime(n) using fasterIsPrime(n). This is straight from the course notes!

  5. nthAdditivePrime(n)
    Write the function nthAdditivePrime(n) that takes a non-negative int n and returns the nth Additive Prime, which is a prime number such that the sum of its digits is also prime. For example, 113 is prime and 1+1+3==5 and 5 is also prime, so 113 is an Additive Prime.

  6. drawDashedLine(canvas, width, height, dashLength)
    Write the function drawDashedLine(canvas, width, height, dashLength) that takes a canvas, width, height, and a positive dashLength, and draws a horizontal dashed line across the middle of the canvas, starting on the left edge, made up of a bunch of small lines of length dashLength followed by gaps also of length dashLength.