Given a positive integer, decide whether it’s a perfect square. For 16 the answer should be True; for 14, False. My immediate reaction was “just take the square root.” Then I read the next line: no built-in math functions. There went my backup plan involving logarithms, too.
Here was my first stab at it. Try one square after another and stop when one hits the target or overshoots:
1 | def func(num): |
I was expecting a time-limit failure. Instead I got a MemoryError on the range(1,num//2) line, before my supposedly expensive comparisons had done much of anything.
What got me unstuck was writing out a few squares in a different way:
- 4 = 1 + 3
- 9 = 1 + 3 + 5
- 16 = 1 + 3 + 5 + 7
Each new square is one odd number away from the last. In general, the first n odd numbers add up to n². That makes the test easy to run backward. Start at 16 and subtract 1, 3, 5, and 7: you land on zero. Start at 14 and the same steps take you past it.
1 | def func(num): |
If the input is n², the loop runs exactly n times.



