Am I Overthinking This Basic Programming Puzzle?
Asked by
+zoom14
I've been stuck for about two hours on what seems like a very basic registration puzzle. I'm a computer science graduate and have worked as a web developer for five years, so I'm starting to wonder whether I'm making this much harder than it needs to be. The problem asks: among the first 393,000 square numbers, what is the sum of all the odd squares? Any hints on how to approach it?
Answers
Take a step back and avoid overcomplicating it. You can simply iterate through the first 393,000 square numbers, check which ones are odd, and add them up. Thatโs an O(N) solution and is more than sufficient here. Also test your code with the sample input and manually calculate a few small cases to confirm the logic.
Reply to this answer
The key observation is that a square is odd exactly when its root is odd. So instead of checking every square, sum the squares of the first 196,500 odd numbers: 1ยฒ + 3ยฒ + 5ยฒ + ... + 392,999ยฒ. You can calculate that with the formula m(4mยฒโ1)/3, where m = 196,500.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions