Let’s First Look At It From A Logical Perspective
How Can We Program A Solution?
Note: For this solution, I will be using python code… To access my work, you can download the .txt file below or access the code through the view link –> use whatever option is easier for you. Then, you can copy and paste it into your compiler. I recommend sublime text or jupyter notebook…. Now, let me walk you through how I was able to create this:
Instead of making one huge function, I broke this problem down into two parts. 1) I first created a function that would check whether a number was a perfect square.
2) Then, I created a for loop, which would simply iterate through the given range and then print the values that result in a square number. Before I continue on to the breakdown of the code, I would like to focus a little bit on how I got to the range of 1 to 23. If we assume that the value of x is 1 away from n, how can we find their values? Well, (x+1)^2 is equal to x^2 + 2x + 1. If the difference between x^2 and n^2 is 45 (by isolating the equation to give us: n^2 – x^2 = 45), we know that 2x + 1 = 45. If 2x + 1 = 45, then x is simply 22, meaning our range can be simplified to (1, 23) (because python ranges are up to but not including).
Using this logic, our code could compile faster and we could also understand a little bit more about the question. Lastly, now that we have solved this problem together, I have a fun problem for you to solve.
Finally, if you enjoyed this article, then please share and leave a nice rating! Thanks.