title: Finding the Maximum Pyramidal Number by recursion in Python
body: <p>I'm given the task to define a function to find the largest pyramidal number. For context, this is what pyramidal numbers are:</p>
  <p>1 = 1^2</p>
  <p>5 = 1^2 + 2^2</p>
  <p>14 = 1^2 + 2^2 + 3^2</p>
  <p>And so on.</p>
  <p>The first part of the question requires me to find iteratively the largest pyramidal number within the range of argument n. To which, I successfully did:</p>
  <pre><code>def largest_square_pyramidal_num(n):
      total = 0
      i = 0
      while total &lt;= n:
          total += i**2
          i += 1
      if total &gt; n:
          return total - (i-1)**2
      else:
          return total
  </code></pre>
  <p>So far, I can catch on.</p>
  <p>The next part of the question then requires me to define the same function, but this time recursively. That's where I was instantly stunned. For the usual recursive functions that I have worked on before, I had always operated <strong>ON</strong> the argument, but had never come across a function where the argument was the condition instead. I struggled for quite a while and ended up with a function I knew clearly would not work. But I simply could not wrap my head around how to &quot;recurse&quot; such function. Here's my obviously-wrong code:</p>
  <pre><code>def largest_square_pyramidal_num_rec(n):
      m = 0
      pyr_number = 0
      pyr_number += m**2
      def pyr_num(m):
          if pyr_number &gt;= n:
              return pyr_number
          else:
              return pyr_num(m+1)
      return pyr_number
  </code></pre>
  <p>I know this is erroneous, and I can say why, but I don't know how to correct it. Does anyone have any advice?</p>
  <p>Edit: At the kind request of a fellow programmer, here is my logic and what I know is wrong:</p>
  <p>Here's my logic: The process that repeats itself is the addition of square numbers to give the pyr num. Hence this is the recursive process. But this isn't what the argument is about, hence I need to redefine the recursive argument. In this case, m, and build up to a pyr num of pyr_number, to which I will compare with the condition of n. I'm used to recursion in decrements, but it doesn't make sense to me (I mean, where to start?) so I attempted to recall the function upwards.
  BUT this clearly isn't right. First of all, I'm sceptical of defining the element m and pyr_num outside of the pyr_num subfunction. Next, m isn't pre-defined. Which is wrong. Lastly and most importantly, the calling of pyr_num will always call back pyr_num = 0. But I cannot figure out another way to write this logic out</p>