Math 350 - Lecture 7

Do, While, For  - Loops!

We’ve arrived at loops - while most Mathematica 
programming can be done in other loop-like 
methods, loops provide fantastic flexibility.

Do

Do[expression[index], {index, values}]

Do[Print[Prime[i]], {i, 1, 10,2}]

Prime /@ Range[10]

Do[expression1; expression2; expression3, {index set}]

Do[j = Prime[i]; Print[i," ", j], {i, 1, 10}]

Problem 7.2 - Consider the formula (n^(2 ))+ n + i. Find the number of consecutive primes produced by this formula for values of i between 1 and 10000.

Select[Range[500], (PrimeQ[#^2 + # + 41] ==False &), 1]

Build this into an answer using a Do loop.

List building trick - A = Union[A, newlist]

A = {1}

A = Union[A, {2, 3}]

A= {};

Do[AppendTo[A,Select[Range[500], (PrimeQ[#^2 + # + i] ==False &), 1]], {i, 1, 10000}]

Ordering[Flatten[A],-2]

Max[Flatten[A]]

A[[17]]

While

While loops are controlled by a Boolean switch.

While[condition, body]

n = 1;
While[!Divisible[n, 17] (* condition *), n++ (* body *);Print[n]];

Problem 7.6 - Find the closest prime number smaller than a given integer m.

m = Input["enter a number"]
While[!PrimeQ[m], m--];
Print[m]

This can be fancied up using more variables so we can print a more complete statement.

m = Input["enter a number"];
Module[{n = m},
While[!PrimeQ[n], n--];
Print["The smallest prime less than ", m, " is ", n,"."]
]

For

For loops let you initialize the loop before it runs and define an increment step outside the body.
For[initialization, condition, increment, body]

For[i = 0, i<4, i++, Print[i]]

For loops can take multiple steps

For[A={};i = 0, i<  5, i++, Print[A];AppendTo[A, i]]

A

Nested Loops

We often need loops inside of loops

Do[Do[Print[i, " ", j], {i, 1, 2}], {j,1,3}]

Or

Do[Print[i, " ", j], {i, 1, 2}, {j, 1, 3}]

Table is really a specialized Do loop

Flatten[Table[{i, j}, {i, 1, 2}, {j, 1, 3}],1]

Problem - Find all pythagorean pairs (m, n)  (that is, the legs of a pythagorean triple) with m, n < 100.

(3, 4) is a Pythagorean pair because 3^2 + 4^2 = a perfect square (5^2)

Sqrt[3^2 + 4^2] is an integer

A = Flatten[Table[{i,j}, {i, 1, 100},{j, i, 100}],1];

A

IntegerQ[Sqrt[#[[1]]^2 + #[[2]]^2]]&@{3,4}

Select[A,IntegerQ[Sqrt[#[[1]]^2 + #[[2]]^2]]&]

Nest

One specific looping operation is composition of functions

This is accomplished with Nest:

Nest[function, input, number of compositions]

Nest[Log,x,5]

We might also want to keep a list of everything performed along the way - NestList

NestList[Log, x, 5]

Instead of a fixed number of iterations, we might want to proceed until a condition is met.

NestWhile[Most, {a, b, c, d, e}, #≠{}&]