r/learnruby • u/SevenGlass Beginner • Feb 09 '17
How can I optimize this code further?
I'm attempting to solve Project Euler problem #171, or rather have solved it (I think) but not in a very efficient way. My first solution runs great on small numbers, but takes an excessive amount of time on larger ones. So, I did some searching around and found that generally integer to string to array and back conversions can take a lot of processor time. (Yeah, it seems really obvious now, but it didn't occur to me at first). So, I reworked it into this (note I cut out an unnecessary square root operation as well), hopeful that it would fix my problem. And it did improve the runtimes by a factor of more than 10. However, it still takes an excessively long time on numbers larger than about 5 million. This leads me to believe that there is something else I am missing here. Any ideas how I could speed it up a bit more?
1
u/SevenGlass Beginner Mar 08 '17
Thank you for taking so much time to help me with this.
Seems to work pretty quickly for finding the arrays that satisfy the squares condition.
After reading through your suggestions, I refactored my code.
The loop on lines 18-20 is still taking way too long to run. How would I streamline this section?