q3.tex 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. \documentclass[11pt]{article}
  2. \usepackage{amsthm,amsmath,amsfonts,amssymb}
  3. \usepackage[ruled,noline,noend]{algorithm2e}
  4. \usepackage[margin=1in]{geometry}
  5. \usepackage{enumerate}
  6. %%% Update the following commands with your name, ID, and acknowledgments.
  7. \newcommand{\YourName}{Tareef Dedhar}
  8. \newcommand{\YourStudentID}{20621325}
  9. \newcommand{\YourAck}{I have completed this question with no outside sources.}
  10. \newenvironment{solution}{\paragraph{Solution.}}{}
  11. \title{
  12. \vspace{-0.8in} \normalsize
  13. \begin{flushright} \YourName \\ \YourStudentID \end{flushright}
  14. \rule{\textwidth}{.5pt}\\[0.4cm] \huge Assignment 1: Question 3 \\
  15. \rule{\textwidth}{2pt}
  16. \vspace{-1in}
  17. }
  18. \date{}
  19. \begin{document}
  20. \maketitle
  21. \paragraph{Acknowledgments.} \YourAck
  22. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  23. \section*{Testing primality [10 marks]}
  24. Analyze the time complexity of the following pseudocode in terms of $n$
  25. using big-$O$ notation.
  26. For this analysis, each operation on integers (including multiplication and squaring) takes constant time.
  27. \begin{algorithm}
  28. \caption{{\sc IsPrime($n$)}}
  29. $j \gets 2$\;
  30. \While{$j^2 \le n$}{
  31. $k \gets 2$\;
  32. \While{$j * k \le n$}{
  33. \If{$j * k = n$}{
  34. \Return False\;
  35. }
  36. $k \gets k+1$\;
  37. }
  38. $j \gets j+1$\;
  39. }
  40. \Return True\;
  41. \end{algorithm}
  42. \begin{solution}
  43. We shall analyze the algorithm in order, by scope blocks. First, we assign j the initial value of 2. This takes constant time. Then, we have a loop. This loop iterates on j, and if we reduce ${j^2} \leq n$ to $j \leq \sqrt{n}$, and notice that j increments one at a time, we can see this loop will iterate $\sqrt{n}$ times in the worst case.
  44. As for what we are doing $\sqrt{n}$ times, we have another loop, from k=2 to j*k$\leq$n (by 1 each time) in the worst case. Since j is at least 2, in the worst case, this loop will iterate n/2 times. This loop performs an if check and multiplication, which are constant time operations, so the inner loop is O(n).
  45. So, since we are looping $\sqrt{n}$ times, and in each of those loops entering another loop of O(n), our total worst-case runtime is O($n\sqrt{n}$).
  46. \end{solution}
  47. \end{document}