Computer Science 15-110, Spring 2011
Class Notes:  Lists and Loops, More Practice (Problem-Solving)


  1. nthHappyPrime
  2. findOddDuplicate
  3. Sample Solutions

Lists and Loops, More Practice (Problem-Solving)
  1. nth Happy Prime
    Background:  for any integer N, add up the squares of its digits.  If this sum is any value besides 1 or 4, do it again, and keep going until you get either 1 or 4.  Interestingly, every number N will eventually get to either 1 or 4 (but not both!).  Numbers that eventually reach 1 are said to be "happy", and numbers that eventually reach 4 are "unhappy".  For example, is N=7 happy?  We sum the square(s) of its digit(s) to get 72, or 49.  Then we do this to our result, 49, to get 42+92, or 97.  And we continue with 97, to get 92+72, or 130.  And we continue with 130, to get 12+32+02, or 10. Continuing, we get 12+02, or 1.  So yes, it is happy!  For more details, see the Wikipedia page on Happy Numbers.

    With this in mind, write the function nthHappyPrime, which takes an integer N and returns the Nth number that is both happy and prime.  We'll start counting from 1, not 0, so nthHappyPrime(1) should return 7 (the smallest number that is both happy and prime).  For any N less than 1, return -1. Here are some test cases for you:
        assert(nthHappyPrime(0) == -1)
        assert(nthHappyPrime(1) == 7)
        assert(nthHappyPrime(10) == 139)
        assert(nthHappyPrime(20) == 383)


  2. Find Odd Duplicate
    Background:  for this problem, we will first consider lists that have this strange property:  while they may be unsorted, we know that every value in the list occurs an even number of times.   So if the list contains 7, for example, it must contain an even number of 7's (maybe 2 of them, maybe 2000 of them, but an even number).  Now, say we take such a list and remove exactly one value from it.  Now, that list has one value that occurs an odd number of times.  Your task is to write the function findOddDuplicate that takes such a list and returns that odd-occurring value.  Here are some test cases for you:
        assert(findOddDuplicate([2, 4, 2, 2, 2, 4, 3, 3, 4, 3, 3, 2, 2]) == 4)
        assert(findOddDuplicate([2, 4, 2, 2, 2, 4, 3, 3, 4, 3, 3, 2, 2, 4, 2]) == 2)
        assert(findOddDuplicate([2, 4, 2, 2, 2, 4, 3, 3, 4, 3, 3, 2, 2, 4, 2, 3, 2]) == 3)

  3. Sample Solutions
    1. nthHappyPrime
    2. findOddDuplicate

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem