Loopy Exercises

Reminder from class demonstrations...  There are two main techniques for repetition in Python: "while" and "for".  Here is an example of each...  Suppose we wanted to add up all the numbers from 1 to 10:

def usingWhile():
   # Note: this is a more verbose solution than actually necessary
   start=1
   end=10
   subtotal=0
   while start <= end:
      subtotal=subtotal+start
      start+=1
   return subtotal

def usingFor():
   subtotal=0
   for i in range(1,11): # Note: this will assign to the variable i the numbers from 1 to 10 (but not 11)
      subtotal+=i    # Note: a+=b  means a = a + b
   return subtotal


Exercises:
 
Put all of the functions into a single file and submit to the homework server.  You must TEST, TEST, TEST before submitting.

1. Create a function called fred(q) = q*q - 3

2. Create the function sumFredWhile(n) that adds up the values if fred(q) for values of q between 0 and n-1.  You must use while rather than for in this function.  And you must also call the fred() function that you created in #1 above.  For example, sumFredWhile (3) = fred(0) + fred(1) + fred(2) = -4

3.  Create the function sumFredFor(n) which does the same thing as sumFredWhile(n) but uses for instead of while.

4. Create the function sumFredBetween(low,high) that adds up values of fred() between fred(low) and fred(high), including both fred(low) and fred(high).   You are guaranteed that 0 <= low < high.  And you MUST use one of the functions in #2 or #3 above.

5. Create the function sumFredBetween2(a,b) which does the same thing as #4 above, except that a might be larger than b or equal to it, but both are non-negative.  You must call sumFredBetween() in this function.

6. Create the function factorPairs(n) which will print out (not return) all of the pairs of factors of the number n.  For instance, when testing factorPairs() in the shell:
>>> factorPairs(24)
1 24
2 12
3 8
4 6
>>> factorPairs(11)
1 11

7. Mini-Challenge Problem: Create the function isPrime(n) that will return True if n is a prime number (n will be an integer greater than 1), and False if n has factors other than 1 and itself.  Examples:

>>> isPrime(23)	
True
>>> isPrime(50)
False
8. Challenge problem: Create the function largestPrimeFactor(n) which will return the largest prime factor of n.  Examples:
largestPrimeFactor(24)  # returns 3
largestPrimeFactor(56)  # returns 7

9. Another Challenge problem:  Here are a few numbers (below).  Can you use your version of isPrime() above to tell which are prime?  Put the answers into the Comments-to-Teacher.  If your version of isPrime() takes too long to answer the questions, perhaps you might try to change your function to make it run faster (do less work to come up with the answer). 

Which of the following numbers are prime?
98767
987127
135797533
12345678911
12345677654381