From the course: Python Essential Training

Unlock the full course today

Join today to access over 23,200 courses taught by industry experts.

Solution: Sum of triangles

Solution: Sum of triangles - Python Tutorial

From the course: Python Essential Training

Solution: Sum of triangles

- [Instructor] The main trick in this challenge is realizing that two triangles, when put together, make a square. Now there is one other trick and that is figuring out which triangles to use. Let's say that we want to get the square of four, four squared or 16. Start with the fourth triangular number, four plus three plus two plus one, which can be arranged in a triangle four tall by four wide, and overlay this on our square. Now, if we were to get another four by four triangle and stick it on top of the square, we can see that it's too big. The diagonals overlap. However, a three by three triangle fits in that corner just fine. And then we get exactly 16. In general, the square of a number, num, is equal to triangle num plus triangle num minus one. The other thing you might have noticed is our friend recursion popping up again. So hopefully you looked at this triangle function. You didn't just take my word for it that it worked. You can see the triangle actually calls itself, it's a…

Contents