Wednesday, February 11, 2009

Simplification of the second loop.

Paste the following code into Mathematica and run it

Clear[a, b, div, remainder, oldremainder, counter, num];
a = 8; b = 5; u = a
If[b > a, {a = b, b = u}]; num = 0; div = a; remainder = b; While[
remainder > 0, {Print[div], oldremainder = remainder,
remainder = Mod[div, remainder], div = oldremainder, num++}];
Print["The Greatest common divisor is " , div];
Print["The Euclidean algorithm required ", num, " steps"]

Note that in this case you got the numbers:
13
8
5
3
2
The Greatest common divisor is 1
The Euclidean algorithm required 4 steps

Try to understand the program and change the numbers to play with it.

No comments:

Post a Comment