Project Euler 229 - Four Representations Using Squares
Official link: https://projecteuler.net/problem=229
Note: I am not happy with my solution since it was brute force and took ~18 mins to run
Thought Process
A complete brute force solutions, surprisingly most solutions in the thread were also brute force.
Here's an outline of what I did:
Start by finding all n's for a^2 + 7b^2
Note that a < sqrt(2,000,000,000), then restrict b accordingly to a
Looped through all possible a, b and put all a^2 + 7b^2 in a set called sqs7
Find all n's for a^2 + 3b^2
Note that a < sqrt(max(sqs7)), then restrict b accordingly to a
Looped through all possible a, b and put all a^2 + 3b^2 that also appeared in sqs7 in a set called sqs3
Find all n's for a^2 + 2b^2
Note that a < sqrt(max(sqs3)), then restrict b accordingly to a
Looped through all possible a, b and put all a^2 + 2b^2 that also appeared in sqs3 in a set called sqs2
Find all n's for a^2 + b^2
Note that a < sqrt(max(sqs2)), then restrict b accordingly to a
Looped through all possible a, b and put all a^2 + b^2 that also appeared in sqs2 in a set called sqs1 (squares 7)
Then the length of sqs1 is the answer.
This code worked for 1,000,000,000 but to compute the final answer I had memory issues, so I just implemented a segmented version of the above and let it run for ~18 mins and voila.
For the segmented version you just have to keep track for each a what was the maximum b. Then in the next segment, you just start from that b.
I selected the segment size to be 2,000,000 but running it a few times and guessing a good segment size.
Interactive Code
My code is too slow so there's no interactive code.
Takes about 6 seconds for 10^7 case, but I include my segmented version code for those struggling with the implementation.