\documentclass{article}
    % General document formatting
    \usepackage[margin=0.7in]{geometry}
    \usepackage[parfill]{parskip}
    \usepackage[utf8]{inputenc}
    \usepackage{amsmath}
    \usepackage{amssymb}
    \usepackage{tikz}
    \usepackage{fancyhdr}
    \usepackage{listings}

\pagestyle{fancy}
\fancyhf{}
\rhead{Edgar Jacob Rivera Rios - A01184125}

\begin{document}
\begin{titlepage}

    \newcommand{\HRule}{\rule{\linewidth}{0.5mm}} % Defines a new command for the horizontal lines, change thickness here

    \center % Center everything on the page

    %----------------------------------------------------------------------------------------
    %	HEADING SECTIONS
    %----------------------------------------------------------------------------------------

    \textsc{\LARGE Tecnológico de Monterrey}\\[1.5cm] % Name of your university/college
    \textsc{\Large Fundamentos de computación}\\[0.5cm] % Major heading such as course name
    %\textsc{\large Minor Heading}\\[0.5cm] % Minor heading such as course title

    %----------------------------------------------------------------------------------------
    %	TITLE SECTION
    %----------------------------------------------------------------------------------------

    \HRule \\[0.4cm]
    { \huge \bfseries Homework 4}\\[0.4cm] % Title of your document
    \HRule \\[1.5cm]

    %----------------------------------------------------------------------------------------
    %	AUTHOR SECTION
    %----------------------------------------------------------------------------------------

    \begin{minipage}{0.4\textwidth}
    \begin{flushleft} \large
    \emph{Student:}\\
    Jacob \textsc{Rivera} % Your name
    \end{flushleft}
    \end{minipage}
    ~
    \begin{minipage}{0.4\textwidth}
    \begin{flushright} \large
    \emph{Professor:} \\
    Dr. Hugo \textsc{Terashima} % Supervisor's Name
    \end{flushright}
    \end{minipage}\\[2cm]

    % If you don't want a supervisor, uncomment the two lines below and remove the section above
    %\Large \emph{Author:}\\
    %John \textsc{Smith}\\[3cm] % Your name

    %----------------------------------------------------------------------------------------
    %	DATE SECTION
    %----------------------------------------------------------------------------------------

    {\large \today}\\[2cm] % Date, change the \today to a set date if you want to be precise

    %----------------------------------------------------------------------------------------
    %	LOGO SECTION
    %----------------------------------------------------------------------------------------

    \includegraphics[width=0.4\textwidth,height=\textheight,keepaspectratio]{logo-tec-negro.png} % Include a department/university logo - this will require the graphicx package

    %----------------------------------------------------------------------------------------

    \vfill % Fill the rest of the page with whitespace

\end{titlepage}

\section{Problems}
Solve the following problems:
\begin{enumerate}
    \item Solve problems 4.58 and 4.59 (Sara Baase)

    \item Assume that the subroutine PARTITION within the quicksort algorithm produces a 9-to-1 split. First, generate the recurrence to compute the complexity of the algorithm under these conditions. Second, estimate  the  complexity  of  the  recurrence  and  discuss  if  the unbalance  in  the  partition  makes  the algorithm to loose the optimality.
    \begin{align*}
        T(n) &\leq cn log (n)\\
        T(n) &= T(\frac{n}{10}) + T(\frac{9}{10}n) + n\\
        &\leq \frac{cn}{10} log(\frac{n}{10}) + \frac{9cn}{10} log(\frac{9n}{10}) + 10\\
        &\leq \frac{cn}{10} log(n) + \frac{cn}{10} log(\frac{1}{10}) + \frac{9cn}{10} log(n) + \frac{9cn}{10} log(\frac{9}{10}) + m\\
        &\leq cn log (n) + \frac{9cn}{10}log(9) - \frac{9cn}{10}log(10) -\frac{cn}{10}log(10) + n\\
        &\leq cn log (n) - n(c log(10) - \frac{9c}{10} log(9) - 1)\\
        T(n) &\leq cn log (n) \text{ if } c log(10) - \frac{9c}{10} log(9) - 1 > 0\\
        &= \theta(n log (n))
    \end{align*}

    The unbalance in the partition would certainly affect the speed of the algorithm, however, the rate of growth would stay approximately the same, and well, we know that at the worst case, which this definitely isn't, the complexity of the quicksort will have an upper bound of $\theta(n^2)$

    \item Show that there is no comparison sorting algorithm whose complexity is linear for at least $n!/2$ inputs of length $n$, What about a fraction $1/n^3$ of inputs of length $n$? What about a fraction $1/2^n$?

    Given that we know that an input of length $n$ has $n!$ permutations, which means that in the worst case, a comparison algorithm has to make at worst $\Omega(n log(n))$ comparisons, which is the height $h$ of the tree. The quantity of inputs which are linear can be represented by $m$. We know that the $n! = 2^h \geq m$, which is equivalent to $h \geq log(m)$ y $log(m) = \Omega(n log(n))$. So, for
    \begin{align*}
        log(\frac{n!}{2}) &= log(n!) - 1 \geq n log (n) - n log(e) -1\\
        log(\frac{1}{n^3}) &=- log(n^3) \leq n log(n)\\
        log(\frac{1}{2^n}) &=- log(n^3) \leq n log(n)
    \end{align*}
    So, for the first one is true that there isn-t a algorithm which is linear for the quantity of inputs stated. However, for the other two, there are algorithms that can be linear, as the number of inputs $m$ that are required to be linear reduces as $n$ increases.

    \item Consider an array of characters $R$, $W$, and $B$, and you want to arrange the array in such a way that the $R$s are first, then the $W$s, and at the end the $B$s. Describe a linear algorithm to accomplish this task.

    As the input space is fairly small compared to other algorithms, a silly but fast algorithm would be to iterate the array and count how many of each characters are in the array, which takes $O(n)$ and then just write the adequate number of $R$, $W$ and $B$ in the required order, which would also only take $O(n)$.

    \item Take a sequence of $2n$ numbers as input. Design an algorithm that partitions the numbers into $n$ pairs, with the property that the partition minimizes the maximum sum of the pair. For example, say we are given the numbers (1,3,5,9). The possible partitions are ((1,3),(5,9)), ((1,5), (3,9)) and((1,9),(3,5)). The pair sums of these partitions are (4,14), (6,12) y (10,8). Thus the third partition has 10 as its maximum sum, which is the minimum over the three partitions. Establish the complexity of your algorithm.

    As the maximum sum can be minimized by pairing the biggest and the smallest elements an each pair subsequently. So we first need to sort the numbers, which can be done in $n log(n)$ and then the joining of the pairs, which can be done in $n/2$ steps, resulting in $n log(n) + \frac{n}{2} = O(nlog(n))$
\end{enumerate}
\end{document}


\documentclass[12pt,letterpaper]{article}

%Packages
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amscd}
\usepackage{dsfont}
\usepackage{enumerate}
\usepackage{fancyhdr}
\usepackage{mathrsfs}
\usepackage{bbm}
\usepackage{framed}
\usepackage{mdframed}
\usepackage{cancel}
\usepackage{float}
\usepackage{mathtools}
%\usepackage[]{mcode}
\usepackage{graphicx}

%Page formatting
\usepackage[letterpaper,voffset=-.5in,bmargin=3cm,footskip=1cm]{geometry}
\setlength{\parindent}{0.0in}
\setlength{\parskip}{0.1in}
\allowdisplaybreaks
\headheight 15pt
\headsep 10pt

% Common Commands
\newcommand\N{\mathbb N}
\newcommand\Z{\mathbb Z}
\newcommand\R{\mathbb R}
\newcommand\Q{\mathbb Q}
\newcommand\lcm{\operatorname{lcm}}
\newcommand\setbuilder[2]{\ensuremath{\left\{#1\;\middle|\;#2\right\}}}
\newcommand\E{\operatorname{E}}
\newcommand\V{\operatorname{V}}
\newcommand\Pow{\ensuremath{\operatorname{\mathcal{P}}}}

\DeclarePairedDelimiter\ceil{\lceil}{\rceil}
\DeclarePairedDelimiter\floor{\lfloor}{\rfloor}

% 22 style
\newcommand\hint[1]{\textbf{Hint}: #1}
\newcommand\note[1]{\textbf{Note}: #1}
\newenvironment{22enumerate}{\begin{enumerate}[a.]\itemsep0em}{\end{enumerate}}
\newenvironment{22itemize}{\begin{itemize}\itemsep0em}{\end{itemize}}
\fancypagestyle{firstpagestyle} {
  \renewcommand{\headrulewidth}{0pt}%
  \lhead{\textbf{CSCI 0220}}%
  \chead{\textbf{Discrete Structures and Probability}}%
  \rhead{Klivans}%
}

\pagestyle{fancyplain}

\newcommand\EX{\mathds{E}}
\newcommand\PR{\mathds{P}}
\newcommand\zlam{Z_\lambda}
\DeclareMathOperator*{\argmin}{arg\,min}

%%%%%%%%%%%%%%%% COMPILE WITH \soltrue or \solfalse %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newif\ifsol
%\soltrue  % SOLUTIONS
\solfalse % NO SOLUTIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}
  \thispagestyle{firstpagestyle}
  \begin{center}
    {\large \textbf{Recitation 1}}

    {\large Numbers and Proofs}
  \end{center}

      \section*{Review}

      \subsection*{Definitions}
      \textbf{Defn 1:} A \textbf{set} is a collection of objects with no repitition.

      \textbf{Defn 2:} $B$ is a \textbf{subset} of $A$ if every element in $B$ is also in $A$. This is written as $B \subseteq A$.

      \textbf{Defn 3:} The \textbf{natural numbers} are the set $\N = \{0,1,2,...\}$. The \textbf{integers} $\Z$ are  $\{..., -2, -1, 0, 1, 2, ...\}$.

      \textbf{Defn 4:} A number $n$ is \textbf{even} if $n = 2k$ for some $k \in \Z$. A number $n$ is \textbf{odd} if $n = 2k + 1$ for some $k \in \Z$.

      \textbf{Defn 5:} A number $n$ is \textbf{rational} if $n = \frac{a}{b}$ for some $a,b \in \Z$.

	\textbf{Defn 6:} $\Pow{(A)}$, called the power set of $A$, is the set of all subsets of $A$. Alternate notation for the power set of $A$ is $2^A$.

      \subsection*{Warm Up}

      Answer true or false to the following problems. Discuss your solutions.

      \begin{enumerate}[a.]
        \item $A$ is any set. Answer true only if the statement is always true.
          \begin{enumerate}[i.]
            \item $A \subseteq A$ \ifsol  (T)  \fi
            \item $\{\} \subseteq A$\ifsol  (T)  \fi
            \item $\{\} \in A$ \ifsol  (F)  \fi
            \item $B:= \{A\}$. $B$ is a set. The notation ``:=" means ``is defined as". \ifsol  (T)  \fi
            \item $C := \{A, A\}$. $C$ is a set. \ifsol  (F, repition) \fi
		 \end{enumerate}
	  \item $A$ is any set and $\Pow{(A)}$ is the set of all subsets of $A$.
		\begin{enumerate}[i.]
		   \item $A \in \Pow{(A)}$  \ifsol  (T)  \fi
		   \item $A \subseteq \Pow{(A)}$  \ifsol  (F)  \fi
		   \item $\emptyset \in \Pow{(A)}$  \ifsol  (T)  \fi
		   \item $\emptyset \subseteq \Pow{(A)}$  \ifsol  (T)  \fi
		   \item $\{A, \emptyset\} \subseteq \Pow{(A)}$  \ifsol  (T)  \fi
          \end{enumerate}
	  \item If $A = \{1,2,4\}$ then $\{2,4\} \in \Pow{(A)}$  \ifsol  (T)  \fi
        \item $\N \subseteq \Z$  \ifsol  (T)  \fi
        \item $\{0, 1, 9\} \subseteq \N$  \ifsol  (T)  \fi
        \item $\{-1.5, 9\} \subseteq \Z$  \ifsol  (F)  \fi
        \item $S$ is the set of students in CS22. $B$ is the set of students at Brown. Jerry is a student in CS22.
        \begin{enumerate}[i.]
          \item $S \subseteq B$  \ifsol  (T)  \fi
          \item \text{Jerry} $\subseteq S$  \ifsol  (F)  \fi
          \item \text{Jerry} $\in S$  \ifsol  (T)  \fi
          \item $\{\text{Jerry}\} \subseteq B$  \ifsol  (T)  \fi
        \end{enumerate}
        \item Let $\mathbb{Q}$ be the set of rational numbers.
        \begin{enumerate}[i.]
          \item $\mathbb{Q} \cap \N = \N$  \ifsol  (T)  \fi
          \item $\mathbb{Q} \cup \N = \R$  \ifsol  (F)  \fi
        \end{enumerate}
        \item \textit{Challenge:} If $B \subseteq A$ and $\exists \ x \in A$ such that $x \not\in B$ then $|B| < |A|$.  \ifsol  (T if finite, F if infinite)  \fi
      \end{enumerate}

	\textbf{Checkpoint - Call a TA over.}

      \section*{Section Lesson - Proof Techniques and Examples}

      \subsection*{Direct Proof}

      A direct proof occurs when you start with what you know, follow a series of steps, and end up with what you are trying to prove.

      Here is an example.

      \textbf{Claim:} If $n$ is odd, then $n^2$ is odd.

      \textbf{Proof (direct):} We know that $n$ is odd, so $n = 2k + 1$ for some $k \in \Z$.

      So $n^2 = (2k+1)(2k+1) = 4k^2 + 4k + 1 = 2(2k^2 + 2k) + 1 = 2m+1$,

      where $m =  2k^2 + 2k$.

      Since $m$ is an integer, $n^2$ is odd. \qed

      \begin{enumerate}[a.]
        \item Prove that the product of an even number and odd number is even.

        \begin{mdframed}
		\ifsol
		Consider $n$ odd and $m$ even. $n = 2a+1$ and $m = 2b$.

		Their product is $(2a + 1)(2b) = 4ab + 2b = 2(2ab + b)$.

		Since $2ab + b$ is an integer their product is even.
		\else
        \vspace{4cm}
		\fi
        \end{mdframed}

        \item Prove that the product of two rational numbers is rational.

		\hint{The product of two integers is an integer.}

        \begin{mdframed}
		\ifsol
		Consider $n = \frac{a}{b}$ and $m = \frac{c}{d}$.

		Their product is $nm = \frac{ac}{bd}$. Since the product of two integers is an integer, we have just expressed $nm$ as the ratio of two integers. Therefore $nm$ is rational.
	 	\else
        \vspace{4cm}
		\fi
        \end{mdframed}

      \end{enumerate}

      \section*{Counterexample}

      Counterexamples help us prove that something is not true.

      For example, suppose Ben makes the claim that if $xy$ is rational then $x$ and $y$ are rational.

      Jerry can disprove his claim by coming up with a counterexample. For example, if $x = \sqrt{2}$ and $y = \sqrt{2}$, then $xy = 2$, which is rational.

      However, you \textbf{cannot} prove a claim by showing one example of it. Jerry has not proven that $x$ and $y$ are irrational, he has just shown that they are not always rational.

      For example, the claim ``all CS22 students like ice cream" can be disproved by finding a student who does not like ice cream. Finding this counterexample, however, will not prove that no students like ice cream.

      Your turn. Disprove the following statements with a counterexample.
      \begin{enumerate}[a.]
       \setcounter{enumi}{2}

        \item If $xyz$ is rational, then $x$, $y$, and $z$ are rational.

        \begin{mdframed}
		\ifsol
		Consider $x = \sqrt{2}$, $y = \sqrt{3}$, $z = \sqrt{6}$. $xyz = 6$ which is rational.
		\else
        \vspace{4cm}
		\fi
        \end{mdframed}

        \item $\Pow{(A\cup B)} = \Pow{(A)}\cup \Pow{(B)}$

        \begin{mdframed}
		\ifsol
		Consider $A = \{1\}$ and $B = \{2\}$.

		Then $\{1,2\} \in \Pow{(A\cup B)}$ but $\{1,2\} \not\in \Pow{(A)}\cup \Pow{(B)}$.
		\else
        \vspace{4cm}
		\fi
        \end{mdframed}

        \item \textit{Challenge - Outside the scope of this class:} All true sentences have proofs.

        \hint{Consider the sentence ``No proof exists for this sentence."}

        \begin{mdframed}
		\ifsol

		\textbf{No proof exists for the sentence:}

		If a proof existed for the sentence ``No proof exists for this sentence" then the sentence would be true. Thereofre, no proof would exist for it. This is a contradiction.

		\textbf{The sentence is true:}

	If the sentence were false then a proof would exist for the sentence and the sentence would therefore be true. This is also a contradiction.

		\textbf{Conclusion:}

	We have therefore shown that there are no proofs for the sentence but the sentence is true.
		\else
        \vspace{6cm}
		\fi
        \end{mdframed}

      \end{enumerate}

	\textbf{Checkpoint - Call a TA over.}

	\section*{Set Element Method}

	How do you prove that $A = B$? First show that $A \subseteq B$ and then you show that $B \subseteq A$. If every element in $A$ is also an element in $B$ and every element in $B$ is also an element of $A$, then $A$ must equal $B$.

	To show that $A \subseteq B$ you consider an arbitrary element in $A$ and show it is also in $B$.

	Here is an example.

	\textbf{Claim:} $A \cap (B \cup C) = (A \cap B) \cup (A \cap C)$

	\textbf{Proof:} We will first show that $A \cap (B \cup C) \subseteq (A \cap B) \cup (A \cap C)$

	Consider an arbitrary element $x$ which is in the set $A \cap (B \cup C)$.
	\begin{align*}
		&x \in A \cap (B \cup C) \\
		\Rightarrow &x \in A \text{ and } \left( x \in B \text{ or } x \in C \right) \\
		\Rightarrow & \left( x \in A \text{ and } x \in B \right) \text{ or } \left( x \in A \text{ and } x \in C\right)\\
		\Rightarrow & x\in (A \cap B) \cup (A \cap C)
	\end{align*}

	Therefore  $A \cap (B \cup C) \subseteq (A \cap B) \cup (A \cap C)$.

	Now we will show that  $ (A \cap B) \cup (A \cap C) \subseteq A \cap (B \cup C)$. Consider an arbitrary element $x$ in the set $(A \cap B) \cup (A \cap C)$.
	\begin{align*}
		&x \in (A \cap B) \cup (A \cap C) \\
		\Rightarrow &  \left( x \in A \text{ and } x \in B \right) \text{ or } \left( x \in A \text{ and } x \in C\right)\\
		\Rightarrow & x \in A \text{ and } \left( x \in B \text{ or } x \in C \right) \\
\Rightarrow  & x \in A \cap (B \cup C)
	\end{align*}
	Therefore $ (A \cap B) \cup (A \cap C) \subseteq A \cap (B \cup C)$ and by the set element method we have proved our claim.

	  \begin{enumerate}[a.]
         \setcounter{enumi}{5}

		\item Prove  $\Pow{(A\cap B)} = \Pow{(A)}\cap \Pow{(B)}$

		\begin{mdframed}
		\ifsol
		\begin{align*}
		&x \in \Pow{(A\cap B)} \\
		\iff & x \subseteq A \cap B \\
		\iff & x \subseteq A \text{ and } x \subseteq B \\
		\iff & x \in \Pow{(A)} \text{ and } x \in \Pow{(B)} \\
		\iff & x \in \Pow{(A)}\cap \Pow{(B)}
		\end{align*} \qed
		\else
		\vspace{6cm}
		\fi
		\end{mdframed}

	\end{enumerate}

      \section*{Proof by contradiction}

      Say we have some statement $T$ that we are trying to prove. Here is how we prove it by contradiction:
      \begin{enumerate}
        \item Assume $T$ is not true.
        \item If $T$ is not true, we arrive at a contradiction.
        \item Since $T$ being false leads us to a contradiction, $T$ must be true.
      \end{enumerate}

      Here is an example.

      \textbf{Claim:} $\N$ is an infinite set.

      \textbf{Proof:} Assume for sake of contradiction that there are a finite number of natural numbers. Then there must be a largest natural number. Say this largest number is $m$.

      However, $m+1$ is still a natural number, and $m+1$ is larger then $m$.

      This is a contradiction, as $m$ is the largest natural number.

      Assuming $\N$ was finite led to a contradiction, and therefore $\N$ is infinite. \qed

	Often the claim that you are trying to prove will be of the form ``If $p$ then $q$." If this is the case, then you assume that $q$ is not true and show that if $q$ is not true then $p$ is not true.  This is called the contrapositive.

      \textbf{Claim:} If $n^2$ is even, then $n$ is even.

      \textbf{Proof:} Assume for sake of contradiction that $n^2$ is even but $n$ is odd. Since $n$ is odd, $n = 2k+1$ for some $k \in \Z$.

      So $n^2 = (2k+1)(2k+1) = 4k^2 + 4k + 1 = 2(2k^2 + 2k) + 1 = 2m+1$.

      Where $m =  2k^2 + 2k$.

      Since $m$ is an integer, $n^2$ is odd. This is a contradiction since $n^2$ is even, and therefore if $n^2$ is even then $n$ must also be even. \qed

      Your turn. Prove the following by contradiction:

      \begin{enumerate}[a.]
         \setcounter{enumi}{6}

        \item 2 is an even number. (Use proof by contradiction by assuming 2 is odd.)

        \begin{mdframed}
		\ifsol
			Assume for sake of contradiction that 2 was odd. Then $2 = 2k+1$ for some integer $k$. Then $k = \frac{1}{2}$ which is a contradiction since $k$ is an integer.
		\else
        \vspace{4cm}
		\fi
        \end{mdframed}

        \item \textit{Challenge - Outside the scope of this class:} There is no integer between 0 and 1.
        \hint{Use the fact that every subset of the natural numbers has a smallest element, and that a natural number squared is still a natural number.}

        \begin{mdframed}
		\ifsol
			Consider the set $S$ which is the set of integers between 0 and 1. Assume for sake of contradiction that this set were non-empty. Then $S$ has a smallest element, which we can call $n$. However, $n^2$ is still between 0 and 1 and is still an integer (since the integers are closed under multiplication). Moreover, $n^2$ is smaller than $n$ which is a contradiction as we assumed that $n$ was the smallest integer between 0 and 1.
		\else
        \vspace{4cm}
		\fi
        \end{mdframed}

        \item \textit{Challenge - Outside the scope of this class:} Consider ``the smallest positive integer not definable in fewer than twelve words". Show that this integer cannot exist.

        \begin{mdframed}
		\ifsol
			Say there was some smallest positive integer not definable in fewer than twelve words. Call this integer $s$. We could then define $s$ in fewer than twelve words by saying ``the smallest positive integer not definable in fewer than twelve words." This is a contradiction.
		\else
        \vspace{4cm}
		\fi
        \end{mdframed}
      \end{enumerate}

		\textbf{Checkpoint - Call a TA over.}
\end{document}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UMB-CS110-2015S: Introduction to Computing
% Copyright 2015 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/UMB-CS110-2015S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def \topDirectory {.}
\def \texDirectory {\topDirectory/src/main/tex}

\documentclass[12pt,letterpaper,twoside]{article}
\usepackage{\texDirectory/template/style/directives}
\usepackage{\texDirectory/template/style/assignment}
\input{\texDirectory/template/config}

\begin{document}

\doc{title}{Solution to Assignment 2}
\doc{date-pub}{Feb 17, 2015 at 5:30 PM}
\doc{date-due}{Mar 03, 2015 at 5:30 PM}
\doc{points}{8}

\prepare{header}

\section*{Question 1}

Write a program \texttt{ShapeDiamond.java} that asks for an integer number \texttt{n} and using \texttt{*} characters, prints a diamond in \texttt{2n-1} rows, such that there is one \texttt{*} character in first row, three \texttt{*} characters in second row and $2n-1$ characters in $n$th row.
Figure \ref{fig1} shows a sample diamond created when user has entered 4 as input integer.
\begin{verbbox}
   *
  ***
 *****
*******
 *****
  ***
   *
\end{verbbox}
\begin{figure}[H]\centering
\theverbbox
\caption{Sample diamond generated in 7 rows} \label{fig1}
\end{figure}

\subsection*{Solution}

\lstset{language=Java}
\lstset{tabsize=2}
\begin{lstlisting}
import java.util.Scanner;
public class ShapeDiamond {
	public static void main (String[] args) {
		Scanner input = new Scanner(System.in);
		// ask user for row number
		System.out.print("Enter number of rows: ");
		int numRows = input.nextInt();
		// close the Scanner as we no longer need it
		input.close();
		int i; // outer loop counter
		int j; // inner loop counter
		for (i=1 ; i <= 2*numRows-1; i++) {
			if (i <= numRows) {
				for (j = numRows; j > i; j--)
					System.out.print(" ");
				for (j = 0; j < 2*i-1; j++)
					System.out.print("*");
				System.out.println("");
			}
			else {
				for (j = 0; j < i-numRows; j++)
					System.out.print(" ");
				for (j = 0; j < 2*(2*numRows-i)-1 ; j++)
					System.out.print("*");
				System.out.println("");
			}
		}
	}
}
\end{lstlisting}

\section*{Question 2}

Remember the Dalton Brothers? Neglecting their original heights, write a program \texttt{Daltons2.java} that asks for heights of Joe, William, Jack and Averell, as well as the order in which they have to be sorted in terms of height. The order is either \texttt{ASC} for shortest to tallest or \texttt{DESC} for tallest to shortest. The program should give names of the brothers in order of their heights as specified.

\subsection*{Solution}

\begin{lstlisting}
import java.util.Scanner;
public class Daltons2 {
	public static void main(String[] args) {
		int i; // loop counter
		int j; // loop counter
		// sorting order: true for ASC, false for DESC
		boolean orderAsc;
		// String array for names of Dalton Brothers
		String[] names = {"Joe", "William", "Jack", "Averell"};
		// Double array for heights of Dalton brothers
		// length of heights[] is determined by number of brothers
		double[] heights = new double[names.length];
		// declaring a Scanner object to get inputs from user
		Scanner input = new Scanner(System.in);

		// Getting height of each brother
		for (i = 0; i < names.length; i++) {
			System.out.print("What is the height of "+names[i]+"? ");
			heights[i] = input.nextDouble();
		}
		// Get order from user
		// a while(true) loop is used to ensure user inserts desired input
		// (This is not the best method to solve this problem, as will be discussed later in class)
		while (true) {
			System.out.print("In which order do you want to sort the Daltons [ASC, DESC]? ");
			// Get a String from user
			String orderName = input.next();
			// check if value of given String matches 'ASC'
			if (orderName.equals("ASC")) {
				orderAsc = true;
				// end while(true) loop
				break;
			}
			// check if value of given String matches 'DESC'
			else if (orderName.equals("DESC")) {
				orderAsc = false;
				// end while(true) loop
				break;
			}
			// if value of String is neither 'ASC' nor 'DESC'
			// prompt user that his input is unacceptable
			// note that the while(true) loop continues after this condition
			else {
				System.out.println("Invalid input.");
			}
		}
		// Close Scanner object as we don't need it anymore
		input.close();
		// if we wanted to show heights we could do it in one line: Arrays.sort(heights)
		// since we are asked to show names sorted based on heights
		// we'll find indices of the sorted heights array.
		double min;
		int[] indices = new int[heights.length];
		boolean[] counted = new boolean[heights.length];
		for (i = 0; i < heights.length; i++)
			counted[i] = false;
		for (i = 0; i < heights.length; i++) {
			min = Double.MAX_VALUE;
			for (j = 0; j < heights.length; j++) {
				if (!counted[j] && heights[j] <= min) {
					min = heights[j];
					indices[i] = j;
				}
			}
			counted[indices[i]] = true;
		}
		// now indices are found, show names based on indices
		for (i = 0; i < heights.length; i++) {
			System.out.println(orderAsc ? names[indices[i]] : names[indices[3-i]]);
		}
	}
}
\end{lstlisting}

\section*{Question 3}

Minnie and Mannie are students of mathematics. Their area of interest is prime numbers. They also work part time in a restaurant. To fight the extreme boredom of their routine tasks at work, they have invented a little somewhat-challenging game between themselves.

Minnie, the waitress, has numbered each item in the menu with a unique \textbf{random} prime number. When Minnie takes orders of a table, she will multiply the menu numbers of all orders placed by that table and gives the final multiplication to Mannie, the chef.

Thanks to his brilliant mind, Mannie will in less than two seconds decompose the given number to its prime factors and prepares the menu numbers corresponding to those factors.

Unfortunately, Mannie is absent this week and you have to replace him. As it is likely that you cannot decompose a number as fast as Mannie, you are requested to write a program \texttt{PrimeMenu.java} that asks for an integer number and prints all prime factors that number is divisible by. Obviously, your program should also indicate how many times the number is divisible by each prime number.

\subsection*{Solution}

\begin{lstlisting}
import java.util.Scanner;
public class PrimeMenu {
	public static void main(String[] args) {
		int i; // loop counter
		int j; // loop counter
		int[] primeList = new int[100000]; // array of primes
		int counter = 0; // counter for array of primes
		boolean definitelyNotPrime; // flag for prime checking
		Scanner input = new Scanner(System.in);

		System.out.print("What is the number? ");
		// ask Minnie the number
		int number = input.nextInt();
		// close scanner since we don't need it anymore
		input.close();
		// Now find all prime numbers less than or equal to half that number
		System.out.print("Calculating...");
		for (i = 2; i <= number/2; i++) {
			// check if a number is prime
			// a number is prime if is not divisible by any smaller prime number
			// note that we can't afford to check if any smaller number divides our number
			definitelyNotPrime = false;
			for (j = 0; j < counter; j++) {
				if (i % primeList[j] == 0) {
					definitelyNotPrime = true;
				}
			}
			if (!definitelyNotPrime) {
				primeList[counter++] = i;
			}
		}
		System.out.println(" OK.");
		System.out.println("Prime\tNumber");
		// Now we know all prime lists to check for
		for (i = 0; i < counter; i++) {
			j = 0;
			while ( number % primeList[i] == 0) {
				number /= primeList[i];
				j++;
			}
			if (j != 0) {
				System.out.println(primeList[i]+"\t"+j);
			}
		}
	}
}
\end{lstlisting}

\end{document}


\documentclass{article}
\input{logproversion}
\usepackage[a4paper]{papersize}
\usepackage{verbatim}
%\usepackage{RCS}
\usepackage{alltt}
\usepackage{xspace}
%\RCS $Id: practicals.tex,v 2.0 2000/02/07 16:46:23 sufrin Exp sufrin $
\title{I(2) Programming Languages\\Logic Programming Laboratories}
\author{Bernard Sufrin}
\date{Version of February 7, 2002}
%
%
\parindent=0pt
\parskip=\medskipamount
\flushbottom
%
%
\def\LOGPRO{{\ttfamily\slshape LogPro}\xspace}
\newenvironment{smalltt}{\begin{small}\begin{alltt}}{\end{alltt}\end{small}}
\def\rmbox#1{\mbox{{\rm #1}}}
%
%
\begin{document}
\maketitle
\begin{abstract}
\noindent This document describes the {\it complete} set of three Labs for the
Programming Languages course. The first two labs are identical to those
in the earlier revision of this document.

\noindent Changes:
\begin{enumerate}
\item  The syntax of \LOGPRO version 1.44 has been extended to accomodate ``fat brackets''.
\item  \LOGPRO  1.44 has different primary and secondary prompts ({\tt --} and {\tt >>} respectively)
\end{enumerate}
\end{abstract}

\section{First Lab}
This Lab is designed to get you acquainted with the \LOGPRO system and
with Prolog.

\begin{enumerate}
\item Read Appendix \ref{Manual} to find out how to run the \LOGPRO system.

\item Define {\tt append} in the usual way, and
\begin{smalltt}
        isrot(XS, YS) :- append(LS, RS, XS), append(RS, LS, YS).
\end{smalltt}

Now find the answers to the query {\tt isrot(1:2:3:nil, YS)}?

What happens if you make the query  {\tt isrot(XS, 1:2:3:nil)}?
Can you explain why?\footnote{You may not be able to answer this
part of the question fully until we have explained the Prolog
execution model more fully in lectures, but if you turn on
tracing in the \LOGPRO interpreter you may be able to describe what is
happening in a little more detail, and that will be
enough for the moment.}

\item In the lectures we partly defined the relation $is$ to implement
basic arithmetic notation.
\begin{smalltt}
        #infix1 is
        #infix4 +
        #infix5 *
        V is V   :- num(V).
        V is E+F :- Ev is E, Fv is F, sum(Ev, Fv, V).
        V is E*F :- Ev is E, Fv is F, prod(Ev, Fv, V).
\end{smalltt}
complete the definition of this relation so that it includes division, subtraction, and
remainder.

\item Investigate, and explain,\footnote{See the previous footnote.} what happens when you try to use {\tt is}
``backwards'', to solve a query such as
\begin{smalltt}
        3 is V+1?
\end{smalltt}

\item Change the definition of {\tt is} so that it works for strings
as well as numbers. Overload (+) to signify catenation as well as addition,
and use \verb.-. and \verb./. for suffix and prefix removal.
\begin{verbatim}
        "foobar" is "foo" + "bar"
        "foo"    is "foobar" - "bar"
        "bar"    is "foobar" / "foo"
\end{verbatim}
Avoid repeated evaluation of the subexpressions of composite
expressions if you can.

\begin{comment}
        #infix1 is
        #infix4 +
        #infix5 *
        V is V   :- num(V).
        V is V   :- str(V).
        V is E+F :- Ev is E, Fv is F, evplus(Ev, Fv, V).
        V is E*F :- Ev is E, Fv is F, prod(Ev, Fv, V).

        evplus(V1, V2, V) :- num(V1), num(V2), sum(V1, V2, V).
        evplus(V1, V2, V) :- str(V1), str(V2), cat(V1, V2, V).
\end{comment}

\end{enumerate}

\section{Second Lab}
A binary tree takes one of the forms

\begin{center}\begin{tabular}{ll}\tt
        leaf(\(E\))             &\rmbox{where \(E\) is a term}
        \\
        \(T\sb1\) ** \(T\sb2\)   &\rmbox{where \(T\sb1\), \(T\sb2\) are binary trees}
\end{tabular}
\end{center}
\begin{enumerate}
\item (``Cat-elimination'')
\begin{enumerate}
\item Define a predicate {\tt flatten/2} such that $flatten(T, L)$ holds
if $L$ is the list formed by the elements at the leaves of the tree $Y$.
For example
\begin{smalltt}
        flatten((leaf(1)**leaf(2))**(leaf(3)**leaf(4)), 1:2:3:4:nil)?
\end{smalltt}
Use the predicate {\tt append/3} to form the list, and investigate
(using the directive {\tt \#count on}) how
many inferences are needed in the best and worst cases when the result list
is of length 4, 8, 12, 16, and 20.

\item Define a predicate {\tt flat/2} with the same specification
as {\tt flatten}, but use open-lists and open-list-append to
form the answer list. Investigate the number of inferences needed in the
best and worst cases as in the previous exercise.

\end{enumerate}
What do you conclude from parts (a) and (b) above?

\item Can either {\tt flatten} or {\tt flat} be used ``backwards'' --
in other words to form a tree from a list?

\item Define a predicate {\tt formtree/2} such that $formtree(L, T)$ holds
if $T$ is a balanced binary tree formed from the elements of the list $L$,
and such that $formtree(L, T)$ holds whenever $flat(T, L)$ holds.

\item Can {\tt formtree/2} be used backwards -- in other words to form a list from a tree?

\end{enumerate}

\section{Third Lab}

In this Lab  we investigate the use of Prolog to prototype the
operational semantics of the Plain language developed in the lectures. With a
modicum of advance preparation the two parts can be taken at one sitting.

We take for granted the following \LOGPRO definitions of
the equality and inequality relations
\begin{smalltt}
        #infix3 "="
        #infix3 "/="
        X=X         :- .
        X/=Y        :- not X=Y.
\end{smalltt}
\def\dom{\mathop{\mathbf{dom}}}

We will represent finite mappings by terms of the form $\{\}$
(for the empty mapping), and $U\mapsto V ~~\&~~ M$ for the mapping
written $M\oplus\{U\mapsto V\}$ in the lecture notes.

\subsection*{Part 1}
The following clauses define the relation $lookup(X, MAP, R)$
which holds between a term $MAP$ (representing a finite mapping $map$),
and terms $X$ and $R$  when $X\in \dom map \land R=map(X)$.\footnote{We have deliberately
left out the clause defining $lookup$ in an empty mapping so that we
can explore the possibility of having ``stuck'' configurations.}
\begin{smalltt}
        #infix6 "|->"
        #infix5 "&"
        lookup(X, U|->V & MAP, V)      :- X=U.
        lookup(X, U|->V & MAP, R)      :- X/=U, lookup(X, MAP, R).
\end{smalltt}

\subsubsection*{Task} Define a relation $update(MAP, X\mapsto Y, MAP')$ which holds
between terms ($MAP, MAP'$) representing mappings ($map, map'$) when
$map'=map\oplus\{X\mapsto Y\}$. In addition: if $X$ is already in the domain of
$map$ then {\em the representation of $map'$ should be no larger
than that of $map$} (in other words should contain no more terms). For example
\begin{smalltt}
        update(                  \{\}, a|->2, a|->2 & \{\})
        update(          a|->1 & \{\}, a|->2, a|->2 & \{\})
        update(b |-> 4 & a|->1 & \{\}, a|->2, b |-> 4 & a|->2 & \{\})
\end{smalltt}

The additional requirement is present to ensure that while
the operational semantics of a program are simulated, the term
representing a store contains no more than a single value for
each variable in the store.\footnote{This is essential if humans
are to be able to make sense of the output of a simulation.}

\subsection*{Part 2}

The inference rules of an operational semantics can often
be modelled by Prolog clauses in which the consequent of the
rule appears as the head of the clause, and the antecedents
as the right hand side. This works satisfactorily only if
the side conditions of the rules are encoded as predicates
and are used as guards ({\it i.e.\/} early) on the right hand
side.\footnote{The notational conventions we use to present
the rules in the lecture notes must also be respected by the
Prolog program, and the best way of doing so is to treat them
as additional side-conditions.}

Here, for example, is an encoding of a few of the Plain rules
as a \LOGPRO program.

\newpage
We start with syntactic declarations
\begin{smalltt}
        #infix0 "-|>"
        #infix3 ";"
        #infix4 ":="
        #infix7 "+"
        #infix7 "-"
\end{smalltt}

Next we define predicates which capture some of the side conditions.
\begin{smalltt}
        id(I)                :- atom(I), I/=skip.
        con(E)               :- num(E).
\end{smalltt}

Our configurations are encoded as \LOGPRO terms in one of the forms\footnote{{\bf NB: the ``fat bracket'' notation is only available in
\LOGPRO versions 1.44 and later. If you don't presently have access to this,
you may encode configurations as {\tt Program | Store} after declaring
{\tt \#infix0 |}}}
\begin{smalltt}
        [| Program    |] Store
        [| Expression |] Store
\end{smalltt}

and our judgements as relations of the form
\begin{smalltt}
        CONFIGURATION -|> CONFIGURATION'
\end{smalltt}

A configuration is in normal form if its program component is {\tt skip}.
\begin{smalltt}
        normalForm([| skip |] S) :- .
\end{smalltt}

We want to show the names of the rules which are used during the execution of
a program, so we define the predicate {\tt rule} and
end each rule by calling it.
\begin{smalltt}
        #notfix rule
        rule S :- show(" (by", S, ")").
\end{smalltt}

The first few rules are encoded as follows\footnote{The rule for identifiers is
not quite the same as that given in the levcture notes, because $lookup$
fails when presented with variables which not already in the store. This is deliberate -- we want to
be able to produce a ``stuck'' configuration easily.}
\begin{smalltt}
    [|  I       |] S        -|>    [|  V     |] S   :- id(I),
                                                       lookup(I, S, V),
                                                       rule "var".

    [|  I:=E    |] S        -|>    [|  skip  |] S'  :- id(I),
                                                       con(E),
                                                       update(S, I|->E, S'),
                                                       rule "assign.2".

    [|  I:=E    |] S        -|>    [|  I:=E' |] S   :- id(I), not con(E),
                                                       [| E |] S -|> [| E' |] S,
                                                       rule "assign.1".

    [|  P; Q    |] S        -|>    [|  P'; Q |] S'  :- P/=skip,
                                                       [| P |] S -|> [| P' |] S',
                                                       rule "seq.1".

    [|  skip; Q |] S        -|>    [|  Q     |] S   :- rule "seq.2".
\end{smalltt}

The {\tt -|>} relation describes only a single step in the (top-level)
execution of a program, although this step may involve the use of
several structural inference rules in addition to any computation rule
it uses.

For example:
\begin{smalltt}
        [| x := 3 ; y := 4 |] \{\}   -|>  CONFIG' ?
         (by assign.2 )
         (by seq.1 )
        CONFIG' = [| skip ; y := 4 |] x |-> 3 & \{\}
\end{smalltt}

The complete program execution relation {\tt -|>* } is encoded as
follows:\footnote{({\it For the theoretically inclined:\/}) Notice that {\tt -|>*} computes a subrelation of
the transitive closure of {\tt -|>}.
In fact it is only the ``stuck'' configurations that are not actually
reached by execution of {\tt -|>*}, even though
the last {\tt show} it executes shows a configuration which is not
in the domain of {\tt -|>}.}
\begin{smalltt}
    #infix0 "-|>*"
    CONFIG  -|>* CONFIG    :- normalForm(CONFIG),
                              show(CONFIG, "  finished.").

    CONFIG  -|>* CONFIG''  :- not(normalForm(CONFIG)),
                              show(CONFIG, "  -|>"),
                              CONFIG  -|> CONFIG',
                              CONFIG' -|>* CONFIG''.
\end{smalltt}

Notice that we take pains to show the configuration at each stage, and to inform the
user when a program has finished.
For example
\begin{alltt}
    ...
    [| x := 3 ; y := x |] \{\}   -|>
     (by assign.2 )
     (by seq.1 )
    [| skip ; y := x |] x |-> 3 & \{\}   -|>
     (by seq.2 )
    [| y := x |] x |-> 3 & \{\}   -|>
     (by var )
     (by assign.1 )
    [| y := 3 |] x |-> 3 & \{\}   -|>
     (by assign.2 )
    [| skip |] x |-> 3 & y |-> 3 & \{\}   finished.
\end{alltt}

If the program is just stuck,\footnote{For the moment the only way this is
possible is if a variable is referenced for which there is not yet a value in the
store.} the ``finished'' epithet is never applied. For example:
\begin{smalltt}
    ...
    [| x := 3 ; y := z |] \{\}   -|>
     (by assign.2 )
     (by seq.1 )
    [| skip ; y := z |] x |-> 3 & \{\}   -|>
     (by seq.2 )
    [| y := z |] x |-> 3 & \{\}   -|>
\end{smalltt}
\subsubsection*{Tasks}

\begin{enumerate}
\item
Encode the rules for addition so that they prescribe a left-to-right
order of evaluation.
\item
Define the following ``driver'' relation
\begin{smalltt}
    #notfix run
    run Program :- [| Program |] \{\} -|>* Config'
\end{smalltt}
and give evidence that the encoding of the rules you gave in part 1
is appropriate  by
running the following predicates.
\begin{smalltt}
        prob1  :- run x:=3 .
        prob2  :- run x:=3; y:=x .
        prob2a :- run x:=3; y:=z .
        prob3  :- run x:=3; y:=4; z:=x .
        prob4  :- run x:=3; y:=4; z:=x+y .
\end{smalltt}
\item
Change the rules for addition so that they no longer prescribe left-to-right
evaluation, and try running {\tt prob4} again. What do you notice?

\item
Encode the rules for {\tt after} and gather evidence of their
appropriateness by running (with the order-prescriptive rules for
addition back in place)
\begin{smalltt}
        prob5 :- run x:=3; y:=4; z:=(x after x:=x+1) .
\end{smalltt}
{\bf Hint:} You will  need to change a few of the rules so that they permit
the evaluation of expressions with side-effects. Make a
note of what happens before you change them.

\item Optional tasks (independent of each other)
\begin{enumerate}
\item ({\it for the moderately ambitious\/})
Encode the rules for conditionals, and gather evidence of
their appropriateness. You will need to add relational operators
to the language. If you are successful in this then encode the iteration rules.

{\bf Hint:}  It is wisest to represent these constructs directly ({\it i.e.} in their
abstract syntax forms, as exemplified below), rather than trying to
find  syntactic declarations for \LOGPRO which make it possible to write them in
the (admittedly more readable) concrete forms given in the notes.
\begin{smalltt}
        if(\(condition\), \(TrueProgram\), \(FalseProgram\))
        while(\(condition\), \(LoopBody\))
\end{smalltt}

\item ({\it for the somewhat persistent\/})
Try running the following predicate
with non-order-prescriptive rules for addition in place
\begin{smalltt}
        prob6 :- run x:=3; y:=4; z:=(x after x:=x+1)+x.
\end{smalltt}
Can you explain what is happening?

Now, if you have time, {\it and you are more than just somewhat persistent\/} try
the following with the same rules in place
\begin{smalltt}
        prob7 :- run x:=3; y:=4; z:=(x after x:=y)+(y after y:=x).
\end{smalltt}
Can you explain what is happening?

\end{enumerate}
\end{enumerate}
%---------------------------------------------------------------------------
\newpage
\appendix
\section{The \LOGPRO Manual (for version \LOGPROVERSION)}\label{Manual}
\newcommand{\sect}[1]{\subsection{#1}}
\newcommand{\subsect}[1]{\subsubsection{#1}}
\input{manual}
%---------------------------------------------------------------------------
\clearpage
\pagenumbering{roman}
\newpage
\tableofcontents
%\RCSSignature

Typeset on \today

\end{document}


% specifies the documnt class. We usually use article but there are others.
\documentclass[a4paper,12pt,oneside]{book}

% these are standard packages used for the math symbols
\usepackage{amsmath,amssymb,amsthm, enumitem, hyperref, tabto}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{fancyhdr}
\usepackage{lastpage}
\usepackage[pdftex]{graphicx}
\usepackage{float}
\graphicspath{ {./Photos/} }

% These commands below is to make sure the numbering of these are consistent with theorem
% If you are not sure what something means, delete them, build a new file and see the
% difference between the files. You can ignore this part for now.
\newtheorem{theorem}{Theorem}[section]
\newtheorem{conjecture}[theorem]{Conjecture}
\newtheorem{observation}[theorem]{Observation}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{example}[theorem]{Example}
\newtheorem{remark}[theorem]{Remark}
\newtheorem{notation}[theorem]{Notation}

% Title of your project
\title{%
  \Huge Ramanujan's Square \\
  \LARGE Detailed Analysis\\
  \Large A DV2136 Project \\
  \large Term Report}

% The author command places text right after title
\author{by \\
\Large Afzal (h1810003) \\
\Large Prannaya Gupta (h1810124) \\
\Large Yap Yuan Xi (h1810166) \\
}

\date{\Large July - September 2019}

\begin{document}
\maketitle

\tableofcontents

\part{An Introduction}

\chapter{Contextualisation}
\section{Why are we doing this?}
We are doing this for our DV2136 Junior Math Project, where we are trying to use this concept to test our skill in the Mathematics. We are also doing this because we are interested in Maths and want to see if we can make something out of what we are given.

\section{Inspiration}
We are working on The Magic Squares because it is a fascinating phenomenon. Being such a fluid structure, that is variable based on just a certain number of dates inputted. Its an interesting concept and we really want to build upon it. We want to extend on this concept so we can see what may behold. We want to try. And we want to see if this paper bears any fruit at all.

\newpage
\section{Magic Squares - A Full-Text Description}

\subsection{Abstract}
In real life situations, some problems relating to division of objects equal in numbers and value can be easily solved by constructing a semi magic square or a magic square in accordance with the given conditions. Mathematics is magic if we can either use one formula for a wide range of applications or the formula itself will produce magic properties.

\subsection{A Brief History of the Magic Square}
Magic squares were known to Chinese mathematicians, and Arab mathematicians, possibly as early as the $7^{th}$ century, when the Arabs conquered northwestern parts of the Indian subcontinent and to learned Indian mathematicians and astronomers, including other aspects of combinatorical mathematics. ‘Cornelius Agrippa’ (1486 B.C. to 1535 B.C.) of China is believed to be the first for construction of magic squares.

\subsection{The Properties of a general Magic Square}
A general Magic Square is the arrangement of random number within the cell such that sum of each row = each column = each diagonal. The common sum is known as ‘Magic Constant’ or ‘Magic Number’. If the above condition is valid only for the sum of elements of rows and columns and not for the diagonal elements, then that array is known as a semi magic square. All magic squares are semi magic squares. A normal magic square contains the integers from 1 to $n^2$. The constant sum in every row, column and diagonal is called the magic constant or magic sum, S. The magic constant of a normal magic square with continuous numbers depends only on n and has the value $S = \frac{n(n^2+1)}{2}$.

\subsection{The Area of Our Investigation}
We are trying to investigate The Ramanujan's Magic Square, a magic square devised by the genius mathematician Srinivasa Ramanujan which has a number of exciting properties.

\newpage
\section{Ramanujan: The Man Who Knew Infinity}
\tab Born in 1887, Ramanujan was a young Indian student.
By the age of 23 Ramanujan was making important new discoveries in mathematics. Professor G.H. Hardy recognised a touch of pure genius in Ramanujan’s theorems. Hardy recognised his talents and arranged to bring Ramanujan to England. Ramanujan decided to accept Hardy’s offer, and on 17 March, 1914 he set out by ship to England.
\subsection{England}
In Cambridge, the young Indian set about working on hundreds of new theorems. Hardy said: “I have never met Ramanujan’s equal.”\cite{studyMagicSquare} However, Ramanujan did not fare so well in his private life. His fragile health suffered. He even became suicidal.
Sadly, Ramanujan never regained his health. He died on 20 April, 1920 in a care home near Madras (now Chennai). He continued working on new theorems even on his death bed. Showing his true Mathematical spirit.\cite{historyRamanujan}

\part{The Beginning : An analysis of our options}

\chapter{How does Ramanujan's Magic Square work?}

\section{What are we looking at? - Primary Basis of our Investigation}
\tab We are investigating Srinivasa Ramanujan's Magic Square. It is noticed that in a normal magic square the columns and rows give the same sum. However in this Magic Square, there are other ways to get the same sum. Like the corners, the diagonals and many more.

\subsection{What we can derive from the square}
\tab This is very intriguing to us and made us want to find out how it works and how this is possible. We want to explore the magic of this mathematical square.

\newpage
\section{Description}
\tab This square has a huge number of possible magic square possibilities. You can consider a huge amount magic square patterns like 'By Row', 'By Column', 'By Quarter'.  Below is a definitive list:

\begin{itemize}
  \item The sum of any column is a number y
  \item The sum of any row is the number y
  \item The sum of any diagonal is the number y
  \item The sum of any 2x2 is the number y (except for those in the middle two columns)
\end{itemize}

However, the real miracle of this square its ability to seemingly morph from one's birthday. The main magic square used as an example is actually derived from Ramanujan's birth date, 22 December 1887, thus amounting the sum y as 139. This is an interesting graphic and provides a majorly interesting phenomenon.

\section{Graphical Representation}
\begin{figure}[H]
\begin{center}
\includegraphics[scale = 0.4]{MagicSquare}
\cite{magicSquare}
\caption{These diagrams show the ways in which the numbers of the Square add up to 139 in the main Ramanujan Square}
\end{center}
\end{figure}

\newpage
\section{Explanation}
\begin{figure}[H]
\begin{center}
\includegraphics[scale = 1.0]{RamanujanSquare}
\cite{ramanujanSquare}
\caption{This diagram shows the algorithm by which the numbers of the Square add up to 139 in the main Ramanujan Square}
\end{center}
\end{figure}

\paragraph{
Let Me Explain: Consider the first row being the derivation.
}
\begin{equation*}
Sum_{given} = DD + MM + CC + YY
\end{equation*}
where DD is the date, MM is the month, CC is the century and YY is the year.

\paragraph{Now consider the first column.}
\begin{equation*}
Sum_{col_1} = DD + (MM-2) + (CC+1) + (YY+1) = DD + MM + CC + YY
\end{equation*}
\subparagraph{Therefore, $Sum_{col_1} = Sum_{given}$}

\paragraph{If you see, this applies for every single property we showed, because the numbers are perfectly balanced.}
\chapter{What will we try to investigate?}

\section{The Theory of Everything (for RMS)}
Is there really a way to sieve out a Ramanujan's Square using algorithmic problem solving separate from the original?

\section{Broken Time: Dimension of Hour}
Is there another dimension to this magic square? If so, what is it?
    \subsection{5x5 Magic Squares}
        Letting H, D, M, C, Y be the hour, the day, the month, the century and the year respectively. \\
        \def\arraystretch{2}
        \begin{center}
            \begin{tabular}{c|c|c|c|c}
                \hline
                 H + 0 & D + 0 & M + 0 & C + 0 & Y + 0  \\
                 \hline
                 D - 2 & C + 1 & Y + 1 & M + 3 & M - 3 \\
                 \hline
                 Y + 2 & M - 1 & D - 1 & H - 2 & C + 2 \\
                 \hline
                 M - 3 & H + 1 & C - 3 & Y + 2 & D + 3 \\
                 \hline
                 C + 3 & Y - 1 & H + 3 & D - 3 & M - 2 \\
                 \hline
            \end{tabular}
        \end{center}
    \subsection{6x6 Magic Squares}
        Letting m, H, D, M, C and Y be the minute, the hour, the day, the month, the century and the year respectively. \\
        \def\arraystretch{2}
        \begin{center}
            \begin{tabular}{|c|c|c|c|c|c|}
                \hline
                 m + 0 & H + 0 & D + 0 & M + 0 & C + 0 & Y + 0  \\
                 \hline
                 M - 1 & Y + 1 & H - 3 & C + 3 & m - 2 & D + 2\\
                 \hline
                 D + 3 & m - 1 & C - 1 & H + 2 & Y - 2 & M - 1\\
                 \hline
                 Y + 2 & C - 4 & M - 3 & D + 1 & H + 3 & M + 1\\
                 \hline
                 H - 2 & D + 2 & m + 4 & Y - 2 & M - 1 & C - 1 \\
                 \hline
                  \\
                 \hline
            \end{tabular}
        \end{center}

\section{Other Forms: Ultimate Disguise}
Are there any other squares with the same properties?

    \subsection{Variation 1: Diagonal}
        Letting D,M,C,Y be the day, month, century and year of the birthday respectively. \\
        Let start with the diagonal. \\
        \def\arraystretch{2}
        \begin{center}
            \begin{tabular}{|c|c|c|c|}
                \hline
                D + 0 & Y + 2 & M - 1 & C - 1 \\
                \hline
                C - 2 & M + 0 & Y - 1 & D + 3 \\
                \hline
                Y + 1 & D + 1 & C + 0 & M - 2 \\
                \hline
                M + 1 & C - 3 & D + 2 & Y + 0 \\
                \hline
            \end{tabular}
        \end{center}
    \subsection{Variation 2: Box}
        Letting D,M,C,Y be the day, month, century and year of the birthday respectively. \\
        Let start with the Upper Left 2 by 2 square. \\
        \def\arraystretch{2}
        \begin{center}
            \begin{tabular}{|c|c|c|c|}
                \hline
                D + 0 & M + 0 & Y - 1 & C + 1 \\
                \hline
                C + 0 & Y + 0 & M - 3 & D + 3 \\
                \hline
                M - 1 & D + 1 & C + 2 & Y - 2 \\
                \hline
                Y + 1 & C - 1 & D + 2 & M - 2 \\
                \hline
            \end{tabular}
        \end{center}

    \subsection{Variation 3: Column}
        Letting D,M,C,Y be the day, month, century and year of the birthday respectively. \\
        Let start with the Left most Column. \\

        \def\arraystretch{2}
        \begin{center}
            \begin{tabular}{|c|c|c|c|}
                \hline
                D + 0 & C + 2 & Y - 1 & M - 1 \\
                \hline
                M + 0 & Y - 2 & C - 1 & D + 3 \\
                \hline
                C + 0 & D + 2 & M + 1 & Y - 3 \\
                \hline
                Y + 0 & M - 2 & D + 1 & C + 1 \\
                \hline
            \end{tabular}
        \end{center}

\section{Super Asymmetry}
Is there any form of derivation of the overall constant without any symmetrical significance?

\section{A Simple Determinant}
How can we use the determinant for this matrix-like square to identify the possible dates when this is happening?

\bibliographystyle{acm}
\bibliography{MainBib.bib}
\end{document}