2017-03-15 HW

posted Mar 15, 2017, 12:16 AM by Samuel Konstantinovich   [ updated Mar 15, 2017, 6:07 AM ]
Goal: Writing a function using loops, and using recursion

Complete the two GCF functions at home if you do not complete them in class.

Euclidean algorithm for Greatest Common Factor
This algorithm is based on the fact that G.C.F. of two numbers divides their difference as well. The math behind it is not important, but the algorithm is:

Calculate the remainder of the greater divided by the smaller. 
This remainder becomes the new smaller number (as it is the smallest of all 3 numbers)
The original smaller number is now the "larger"

Repeat until the remainder is 0.

For example, if we want to find the G.C.F. of 54 and 24:
Divide 54 by 24. The remainder is 6
24 is the larger
6 is the smaller
Repeat the process:
Now, we divide 24 by 6 and the remainder is 0. Hence, 6 is the required G.C.F

Can you easily find the G.C.F of 40 and 192 this way?
192,40 -> 32
40,32  -> 8
32,8 -> 0
8,0 STOP!

gcf(54,24) results in 6
gcf(192,40) results in 8

1. Write this using a loop.  gcfLoop(a,b)
-When should the loop stop?

2. Write this using recursion: gcfRec(a,b)  , make sure you call gcfRec, NOT gcfLoop in your function!!
Think of these two "rules" for recursion:
-If I can solve the problem now, without recursion, the function simply returns a value. (base case) 
-If I cannot solve the problem now without recursion, the function reduces the problem to something smaller and similar and calls itself to solve the problem. (recursive case)