\(\(\("Putting stuff in quotes allows you to write comments. To compile a line, you need to press SHIFT-ENTER. Do not compile the instruction lines unless you want to see these lines printed again."\)\(
\)
    \) (*\ 
      anything\ between\ these\ is\ commented\ out\ and\ not\ displayed\ *) \)

num  =  4 *5 ;

num

num  =  4 * 5

num  =  
      4 5 / 2 3

(* 
      Many standard functions start off with a capital letter and then the name;  
      the argument is in braces .  
          We can have many things in one input block,  
      just hit return after each. *) 
 (* Note E is 2.71828 ... ,  Pi is 3.14159 ... ,  
      I is the sqrt (-1),   ...  *) 
a  =  Cos[1.0]

    b  =  Sin[1.0]

    c  =  Sqrt[a - b]

    d  =  Log[10, 100]

    e  =  Exp[-10.0]

    E

    Pi

    I

M  =  { {1, 2, 3},  {4, 
          5, 6},  {0, 8, 9}}

MatrixForm[M]

M2  =  M . M

"The above multiplies two matrices. We'll now calculate some basic \
quantities."

InvM  =  Inverse[M]
MatrixForm[InvM]

c  =  Eigenvalues[M]

"On some versions of mathematica, when you compile the above it gives \
Root[blah]. This is because the answer is 
not exact. To get an exact answer, we use the Numerical Command, N. We first \
give an example. If we type Pi, we get the exact
answer (a symbol). If we type N[Pi], it gives us a few digits. If we need \
more digits, do N[Pi,numdigitsneed]"

Pi

N[Pi]

N[Pi,  20]

c  =  N[ Eigenvalues[M],  10 ]

"Notice we now have numerical values of the eigenvalues (to 10 \
digits). These values are stored, and we can pull off entries
one at a time."

c[[1]]

N[ c[[1]] ]

"Note how we were able to store the eigenvalues in a vector, and then \
read off the components. Sometimes we need single brackets, sometimes we need \
double brackets.
Using N[ ... ] gives numerical values."

MM  =  Table[Random[],  {m, 4},  {n,  4}]

MatrixForm[MM]

"The above generates a random 4x4 matrix with entries chosen from the \
uniform distribution."

Plot[ Sin[x],  {x, 0, 2 Pi}]

Plot[{Sin[x],  Cos[x]},  {x, 0, 2 Pi}]

Plot3D[ Sin[x] Cos[y],  {x, 0, Pi},  {y,  0,  Pi}]

Integrate[ t Exp[-t^2],  {t, 0, x}]

NIntegrate[ t Exp[-t^2],  {t, 0, 2}]

(* 
      we now show how to define functions .  
          We use underscore by the variable names *) 
nthprime[n_]  :=  Prime[n] ;  (* 
      this gives the nth prime *)

nthprime[10]
nthprime[9]

diffnthprime[n_]  :=  
        nthprime[n]  -  nthprime[n - 1] ;

diffnthprime[10]

powersum[n_, k_]  :=  Sum[ i^k,  {i, 0, n}]

powersum[100, 2]

\(\(\( (*\ 
      we\ now\ show\ how\ to\ define\ functions . \ 
          We\ use\ underscore\ by\ the\ variable\ names, \ 
      and\ then\ Module\ followed\ by\ braces . \ 
          Whatever\ is\ inside\ the\ braces\ are\ local\ variables, \ 
      known\ only\ to\ this\ procedure\ or\ function . \ 
          If\ we\ write\ something\ equals\ {}\ then\ we' 
        ve\ initialized\ it\ to\ be\ the\ empty\ \(\(array\)\(.\)\)\ *) \)\(
\)\( (*\ 
      this\ function\ counts\ the\ number\ of\ solutions\ to\ x^2\  + \ 
          y^2\  = \ a\ modulo\ n; \ it\ has\ two\ inputs, \ 
      n\ and\ \(\(a\)\(.\)\)\ *) \)\(
\)\( (*\ 
      we\ find\ all\ solutions\ and\ store\ it\ in\ an\ array; \ 
      as\ we\ want\ to\ be\ able\ to\ access\ this\ array\ afterwards, \ 
      we\ do\ not\ have\ it\ as\ a\ local\ but\ rather\ global\ variable, \ 
      ie, \ not\ inside\ the\ braces\ inside\ the\ \(\(module\)\(.\)\)\ *) \)\(
\)\(NumSolns[n_, a_]\  := \ 
        Module[{x, y, count}, \  (*\ 
            we\ put\ the\ local\ variables\ in\ braces\ after\ module\ *) 
count\  = \ 0; \  (*\ we\ initialize\ count, \ 
            the\ number\ of\ solns, \ to\ zero\ *) 
Clear[
            ListOfSolns]; \  (*\ if\ we\ had\ used\ ListOfSolns\ before, \ 
            this\ clears\ it\ *) 
ListOfSolns\  = \ {}; \  (*\ we\ set\ ListOfSolns\ to\ the\ empty\ array\ *) 
For\ [
            x\  = \ 0, \ 
            x\  ≤ \ n - 1, \ \(x++\), \  (*\ 
              how\ we\ do\ a\ for\ loop\ *) 
{\ \  (*\ 
                starting\ brace\ of\ the\ for\ loop\ *) 
For\ [y\  = \ 0, \ 
                y ≤ \ 
                  n - 1, \ \(y++\), 
{
If[\ 
                    Mod[x^2\  + \ y^2\  - \ a, 
                        n]\  == \ \ 0, \ 
{\ 
Print["We found a solution: (x,y) = (", \ 
                        x, \ ", ", \ y, \ ")."]; \  (*\ 
                        prints\ the\ found\ solution\ *) 
\ 
                      count\  = \ count + 1; \  (*\ 
                        
                        increases\ count\ by\ 1\ to\ indicate\ found\ a\ soln\ *) 
ListOfSolns\  = \ 
                        Append[ListOfSolns, \ {x, y}]; \  (*\ 
                        adds\ to\ list\ of\ solns\ *) 
}
]; \  (*\ 
                    end\ of\ If\ loop\ *) 
}]; \  (*\ 
                end\ of\ y\ For\ loop\ *) 
}\ ];  (*\ 
            end\ of\ x\ For\ loop\ *) 
Print["The number of solutions when the modulus = ", \ n, \ ", a = ", \ 
            a, \ " is equal to ", \ 
            count];
];\)\)\)

NumSolns[5, 
      1]

    ListOfSolns

    count

ListOfSolns[[1]]   

    ListOfSolns[[1, 1]]   

    ListOfSolns[[1]][[1]]

<< Graphics`Graphics`
<< Statistics`DataManipulation`
<< Statistics`NormalDistribution`   
  

      
UniformDiff[numdo_]  :=  
        Module[{i }, 
ValueList  =  {};   (* 
            initializes to the empty list *) 
DiffList  =  {};   (* 
            initializes to the empty list *) 
For[
            i  =  1,  
            i  ≤  
              numdo,  i++, 
ValueList  =  
                Append[ValueList,  Random[]];
];   (* 
            end of i For loop *) 

ValueList  =  
            Sort[ValueList];   (* 
            this sorts the list into increasing order *) 

For[i  =  1,  
            i  ≤  
              numdo  -  
                1,  i++, 
{
DiffList  =  
                  Append[DiffList,  (ValueList[[i + 1]]  -  
                          ValueList[[i]]) * 
                      numdo];
}  (* 
              we use braces to begin and end statements in the for loop;  there is no need here as there is only one statement in the for loop. *) 
];   (* 
            end of i For loop *) 

 
          Histogram[ DiffList];    (* 
            this prints a histogram *) 
 (* 
            the second line scales the histogram so that we have percents and not total numbers *) 
Histogram[
            DiffList,  HistogramCategories  ->  bincat,  
            HistogramScale  ->  
              1];

];

UniformDiff[1000]

"We now load in a package, the statistical package on Continuous \
Distributions. It has a lot of nice distributions,
for example, the Gaussian distribution. we will save the Gaussian \
distribution to the name gdist."

<< Statistics`ContinuousDistributions`

gdist  =  NormalDistribution[0, 1]

NN  =  
      MatrixForm[  Table[
          Random[gdist],  {m,  4},  {n, 4} ]  ]

"This allows us to load in a statistics package and generate matrices \
with entries from a normal distribution. Watch what happens to the entries as \
we change the standard deviation."

gdist2  =  NormalDistribution[0, 10]

NN  =  
      MatrixForm[  Table[
          Random[gdist2],  {m, 4},  {n, 4} ]  ]

Det[NN]

"Notice we do NOT get the determinant. The problem is that NN is NOT \
a matrix, but a DISPLAYED matrix."

NNN  =  Table[Random[gdist2],  {m, 4},  {n, 4} ]

Det[NNN]

"To define a function, one needs to do an underscore after each \
variable, and := instead of ="

f[x_, y_, z_]  :=  Sin[x  +  y] * z^2

f[1, 2, 3]

"To get numerical values, one can use 1.0 instead of 1"

f[1.0, 2, 3]

"you can do multiple statements on one line if you separate with a \
semi-colon. Only the output of the last is displayed. Here, g[n] is the nth \
prime number."

g[n_]  :=  Prime[n]

g[2];   g[3]  
g[4]

G[x_]  :=  Sum[ n,  {n, 1, Floor[x]}]

Plot[ G[x],  {x, 1, 10}]

"You can also plot several functions at once."

Plot[ {G[x],   .5*x * (x + 1)  +  0* x*Sin[6 x]},  {x,  
        1,  25} ]

"Mathematica also supports IF and FOR statements"

Mod[12, 7]

"The above is the mod function: 12 mod 7 is 5"

h[x_]  :=  
      If[ Mod[ Floor[x],  2]  ==  1,  5,  -5]

Plot[ h[x],  {x, -5, 5}]

"If statements work by IF[Condition, Then This, Else This]. You can \
have nested IF statements"

\(h[x_]\  := \ 
      If[\ Mod[\ Floor[x], \ 3]\  == \ 0, \ 
        0, \ 
		\ \ \ \ \ \ If[\ 
          Mod[\ Floor[x], \ 3]\  == \ 1, \ 1, \ 
          2]
\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ]\)

Plot[ h[x],  {x, 0, 9}]

IntegerQ[Sqrt[21222079685]]

"We now include a quick program to calculate eigenvalues of Toeplitz \
Matrices. This code can easily be 
modified for other investigations."

"First we make sure we have loaded in the packages we need."

<< Graphics`Graphics`

<< Statistics`DataManipulation`
<< Statistics`NormalDistribution`

ndist  =  NormalDistribution[0, 1];

"In the program below, we calculate num matrices, each is n x n. we \
choose the entries randomly from the standard normal
distribution subject to being a real symmetric toeplitz matrix with zeros on \
the main diagonal. remember a toeplitz matrix is constant along diagonals. we \
normalize the eigenvalues by
sqrt[n]. we also have some if statements that print based on where we are -- \
the point is to know how much longer the program
will have to run. we then create a histogram."

\(\(\(
\)\(TopMatnodiag[n_, \ num_]\  := \ 
        Module[\ {aa, \ b}, \ 
\ \ \ \ \ \ \ \ Clear[
            temp]; 
\ \ \ \ \ \ \ \ temp\  = \ {}; \ 
\ \ \ \ \ \ \ \ For[aa\  = \ 1, \ 
            aa\  ≤ \ 
              num, \ \(aa++\), 
\ \ \ \ \ \ \ \ \ {
\ \ \ \ \ \ \ \ \ \ Clear[
                a]; 
\ \ \ \ \ \ \ \ \ For[i\  = \ 1, \ 
                i\  ≤ \ n, \ \(i++\), \ 
                a[i, i]\  = \ 0]; \ \ \  (*\ initializes\ a, \ 
                a\ two - dimensional\ array, \ 
                to\ all\ zeros\ *) 
		
\ \ \ \ \ \ \ \ \ For[k\  = \ 2, \ 
                k\  ≤ \ 
                  n, \ \(k++\), 
	{
\ \ \ \ \ \ \ \ \ \ ran1\  = \ Random[ndist]\ ; 
	\ \ For[
                    i = 1, \ 
                    i\  ≤ \ 
                      n\  - \ k\  + \ 
                        1, \ \(i++\), 
\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ {\ \(a[\ i, \ 
                            k\  - 1\  + \ i]\  = \ \ \(a[
                              k\ \  - \ 1\  + \ i, \ \ i]\  = \ 
                            ran1\);\)\ \ \ }\ \ 
	\ \ \ \ \ \ \ ]; \  (*\ end\ of\ i\ for\ loop\ *) 
	}]; \  (*\ 
                end\ of\ k\ for\ loop\ *) 
 (*\ 
                this\ makes\ a, \ a\ 2 - dim\ array, \ 
                toeplitz\ *) 

\ \ \ \ \ \ \ \ \ \ \ \ mat\  = \ Array[\ a, \ {n, n}]; \  (*\ 
                this\ makes\ a\ matrix\ from\ a\ *) 
\ \ \ \ \ \ \ \ \ \ \ \ tempev\  = \ \ N[
                  Eigenvalues[mat]\ /\ 
                    Sqrt[1.0*
                        n]]\ ; 
\ \ \ \ \ \ \ \ \ \ \ \ If[\ Mod[aa, \ 20]\  == \ 0, \ Print["We're at aa = ", \ aa]]; \  (*\ 
                this\ prints\ every\ 20\ lines; \ 
                the\ advantage\ of\ such\ a\ line\ of\ code\ is\ that\ for\ long\ programs, \ 
                you\ get\ a\ sense\ of\ how\ long\ it\ has\ run\ *) 
	\ \ \ For[b\  = \ 1, \ 
                b ≤ \ 
                  n, \ \(b++\), \ \(temp\  = \ 
                    Append[\ temp, \ 
                      tempev[\([b]\)]\ ]\ ;\)\ \ ];
\ \ \ \ \ \ \ \ \ }\ ]; \  (*\ 
            end\ of\ aa\ loop\ *) 

\ 
          Histogram[\ temp\ ]; \ 
 (*\ 
            the\ second\ line\ scales\ the\ histogram\ so\ that\ we\ have\ percents\ and\ not\ total\ numbers\ *) 
Histogram[temp, \ 
            HistogramCategories\  -> \ bincat, \ 
            HistogramScale\  -> \ 
              1];
\ \ ];\)\)\)

TopMatnodiag[10, 100]

\("Below is some code for investigating 3x+1 and its generalizations"\)

RemoveTwo[x_]  :=  
      Module[{i},  i  =  x;  
        While[  Mod[i, 2]  ==  0,  i  =  i / 2];  
        Return[i]]

F3[x_]  :=  
        RemoveTwo[ 3*RemoveTwo[x]  +  1];
F5[x_]  :=  RemoveTwo[ 5*RemoveTwo[x]  +  1];

"We now give a code to check the first digits of the 3x+1 \
problem"

ben3[start_,  num_]  :=  
        Module[ {d, m, j, x}, 
For[m = 1,  
            m ≤  9,  m++,  
            numdig[m]  =  0]; 
x  =  
            start; 
count  =  0; 
For[
            j  =  1,  
            j  ≤  
              num,  j++, 
{
  
numdig[   Mod[  Floor[
                      x*1.0 / 10^Floor[Log [10,  x]] ],  
                    10 ] ]++; 
count  =  
                count + 1; 
x  =  
                F3[x]; 
If[x  ==  1,  
                j  =  num  +  
                    5];
}]; 
bF[
              y_]  :=  numdig[Floor[y  +   .5]] /
              count; 
ben[y_]  :=  
            Log[10,  
              1  +  (1.0/y)]; 
Plot[ {bF[y],  
              ben[y]},  {y,  .5, 
              9.5}]; 
Print["Count (the number of terms \
before we hit one) = ",  
            count]; 
Print["The number is approximately \
10^",  Floor[Log[10, 1.0 start]]];
];

ben3[
      4543534664576457754636456464754385784375987684937639847649837698374457457745, 1000]

"The following compares the terms of 5x+1 to a geometric brownian \
motion and the first digits of the
terms to Benford's law."

\(glog[x_, \ end_]\  := \ 
      Module[\ {numat, \ tempplot, \ numdig, \ lognumdig, \ m, y, \ 
          temp}, 
Clear[tempplot]; \ 
        Clear[temp]; 
For[m\  = \ 1, \ 
          m\  ≤ \ 9, \ \(m++\), \ {\ lognumdig[m]\  = \ 0; \ 
            numdig[m]\  = \ 
              0;\ }\ ]; 
tempplot\  = \ {\ {0, 
              0}\ }; 
numat\  = \ 
          RemoveTwo[x]; \ 
\ \ \ \ For[j = \ 1, \ 
            j\  ≤ \ 
              end, \ \ \(j++\), \ 
\ \ \ \ \ \ {\ \ 
If[\ 
                Mod[j, \ 1000]\  == \ 
                  0, \ \(Print["j = ", \ j, \ " x = ", \ 
                    numat, \ " and goes to ", \ 
                    F[numat]];\)\ ]; 
AppendTo[\ 
                tempplot, \ {j, \ 
                  Log[E, numat]}\ ]; 
AppendTo[\ 
                tempplot, \ \ {j, \ 
                  Log[E, \ 1.25]\ *\ j\  + \ 
                    Log[E, x]}]; 
\(numdig[\ \ \ Mod[\ \ Floor[numat*1.0\ /\ 10^Floor[Log\ [10, \ numat]]\ ], \ 
                    10\ ]\ ]++\); 
temp\  = \ 
                Exp[Log[10, \ numat]\  - \ 
                    j*Log[10, \ 
                        1.25]]; 
\(lognumdig[\ \ \ Mod[\ \ Floor[temp*1.0\ /\ 10^Floor[Log\ [10, \ temp]]\ ], \ 
                    10\ ]\ ]++\); 
numat\  = \ 
                5\ *\ numat + \ 1; \ \  (*\ 
                doing\ the\ 5  x + 
                  1\ problem\ *) 
\ }\ 
]\ 
ListPlot[\ tempplot, \ 
            PlotJoined\  -> False]\ ; 
Clear[
          tempplot]; \ 
        tempplot\  = \ {\ {0, 0}\ }; 
For[\ m\  = \ 1, \ 
          m\  ≤ \ 9, \ \(m++\), \ 
          AppendTo[
            tempplot, \ {m, \ 
              1.0*numdig[m]\ /\ end}]]; 
ListPlot[\ 
          tempplot]; 
Clear[
          tempplot]; 

bF[y_]\  := \ 
          numdig[Floor[y\  + \  .5]]\ /\ end; 
ben[
            y_]\  := \ Log[10, \ 
            1\  + \ \((1.0/y)\)]; 
Plot[\ {bF[y], \ 
            ben[y]}, \ {y,  .5, 
            9.5}]; 

\ 
        tempplot\  = \ {\ {0, 0}\ }; 
For[\ m\  = \ 1, \ 
          m\  ≤ \ 9, \ \(m++\), \ 
          AppendTo[
            tempplot, \ {m, \ 
              1.0*lognumdig[m]\ /\ end}]]; 
 (*\ \(ListPlot[
              tempplot];\)\ *) 

logbF[
            y_]\  := \ lognumdig[Floor[y\  + \  .5]]\ /\ 
            end; 
Plot[\ {logbF[y], \ ben[y]}, \ {y,  .5, 
            9.5}];
\ ]\)

glog[421, 1500]

\(\(\( (*\ 
      does\ the\ josephus\ problem\ for\ k\  <= \ 
        4\ *) \)\(
\)\( (*\ 
      you\ have\ n\ people\ in\ a\ circle, \ 
      person\ one\ starts\ with\ a\ gun\ and\ kills\ the\ k - 
        1  st\ person\ from\ him\ and\ then\ passes\ the\ gun\ to\ the\ next\ person\ on\ the\ circle . \ 
            this\ continues\ until\ only\ 1\ person\ is\ \(\(left\)\(.\)\)\ *) \)\(
\)\(josp[n_, \ k_]\  := \ 
        Module[{}, 
nlist\  = \ {}; 
count\  = \ 0; 
For[i\  = \ 1, \ 
            i\  ≤ \ n, \ \(i++\), \ 
            nlist\  = \ 
              AppendTo[nlist, i]]; 
listlength\  = \ 
            Length[nlist]; 
Print[
            nlist]; 
While[
            listlength\  ≥ \ k\  && \ 
              count\  ≤ \ 
                n, 
{
count\  = \ 
                count + 1; \  (*\ 
                makes\ sure\ coding\ error\ doesn' t\ have\ program\ run\ 4  
                  ever*) 
newlist\  = \ {}; 
tempnewlist\  = \ {}; 
last\  = \ 
                0; 
If[
                Mod[listlength, k]\  == \ 
                  0, 
{
\(For[
                      i\  = \ 1, \ 
                      i\  ≤ \ 
                        listlength, \ \(i++\), 
\(If[
                          Mod[i, k]\  ≠ \ 
                            0, \ \(newlist\  = \ 
                              AppendTo[newlist, 
                                nlist[\([i]\)]];\)];\)];\)
}]; 

If[
                Mod[listlength, k]\  != \ 
                  0, \ 
{
tempnewlist\  = \ {}; 
For[i\  = \ 1, \ 
                    i\  ≤ \ 
                      k*Floor[
                          listlength/k], \ \(i++\), 
\(If[
                        Mod[i, k]\  ≠ \ 
                          0, \ \(tempnewlist\  = \ 
                            AppendTo[tempnewlist, 
                              nlist[\([i]\)]];\)];\)]; 
newlist\  = \ {}; 
remainder\  = \ 
                    listlength\  - \ 
                      k*\ Floor[listlength/k]; 
For[
                    i\  = \ k*\ Floor[listlength/k] + 1, \ 
                    i\  <= \ listlength, \ \(i++\), \ 
                    newlist\  = \ 
                      AppendTo[newlist, \ 
                        nlist[\([i]\)]]]; 
For[i\  = \ 1, \ 
                    i\  ≤ \ 
                      Length[tempnewlist], \ \(i++\), 
newlist\  = \ 
                      AppendTo[newlist, 
                        tempnewlist[\([i]\)]]];
}]; 

nlist\  = \ 
                newlist; 
Print[
                nlist]; 
listlength\  = \ 
                Length[nlist];

}]; 

If[k\  == \ 3, \ 
            Print["{", nlist[\([2]\)], "}"]]; 
If[
            k\ \  == \ 4\  && \ Length[nlist]\  == \ 2, \ 
            Print["{", nlist[\([1]\)], "}"]]; 
If[
            k\  == \ 3\  && \ Length[nlist]\  == \ 3, 
            Print["{", 
              nlist[\([2]\)], "}"]];

];\)\)\)

josp[25, 2]

(* 
      this program will find all 3 x 3 magic squares with rows and columns and diagonals summing to 15.  *) 
ninelist  =  {1, 2, 3, 4, 5, 6, 7, 8, 9};

    permninelist  =  Permutations[ninelist];

    For[j  =  1,  
        j  ≤  9!,  j++, 
{
For[i  =  1,  
            i  ≤  
              9,  i++, 
{
matrix[
                    i]  =  permninelist[[j]][[i]];
}]; 
rows  =  
            0; 
columns  =  
            0; 
diag  =  0; 
If[ 
            matrix[1]  +  matrix[2]  +  matrix[3]  ==  15  &&  
              matrix[4]  +  matrix[5]  +  matrix[6]  ==  
                15  &&  matrix[7]  +  matrix[8]  +  
                  matrix[9]  ==  15,  
            rows  =  1]; 

If[ 
            matrix[1]  +  matrix[4]  +  matrix[7]  ==  15  &&  
              matrix[2]  +  matrix[5]  +  matrix[8]  ==  
                15  &&  matrix[3]  +  matrix[6]  +  
                  matrix[9]  ==  15,  
            columns  =  1]; 

If[ 
            matrix[1]  +  matrix[4]  +  matrix[9]  ==  
              matrix[3]  +  matrix[4]  +  matrix[7],  
            diag  =  1]; 

If[
            rows  ==  1  &&  columns  ==  1  &&  
              diag  ==  1, 
Print[
                MatrixForm[{{matrix[1], matrix[2], matrix[3]}, {matrix[4], 
                      matrix[5], matrix[6]}, {matrix[7], matrix[8], 
                      matrix[9]}}]];];

}];