3 ms·
Wow, 5 minutes in Ruby, and less than a second in Go? I know scripting languages are slow, but it's easy to forget just how much slower. (EDIT: Corrected misrea
by electrograv 13y ago
Wow, 5 minutes in Ruby, and less than a second in Go? I know scripting languages are slow, but it's easy to forget just how much slower. (EDIT: Corrected misread number thanks to dljsjr).
I don't want to detract from the article's main point with a cliche "algorithmic optimization beats fine tuning", but I think it's worth mentioning. Unless I'm mistaken, this particular problem can be solved about 10,000,000x more efficiently.
> Given two numbers X and Y, return how many numbers in that range
> (inclusive) are palindromes, and also the square of a palindrome.
I would just count the digits of X and Y, then ranging between those counts, apply the following algorithm: For N digits, enumerate all numbers of N/2 digits satisfying the bounds X and Y. If N is even then simply mirror the first N/2 digits. If N is odd, mirror the first N/2-1. Finally, check the bounds of the resulting number against X and Y to filter out edge cases.
If the original algorithm runs in 10^N time, this would be 10^(N/2). For N=14 as mentioned, that's roughly a speedup of 10,000,000.
Edit: It seems I misinterpreted the question (which sounds like you're supposed to enumerate all palindrome numbers X>=N>=Y, and also print out the squares of those numbers). This is actually asking for a particular type of palindromes -- those which are palindromic squares of palindromes. As macobo helpfully points out, you can drastically optimize mathematically from this additional filter.
- dljsjr 13y agoNo, 5 minutes in Ruby vs < 1s in Go. OP's last benchmark was only for the iteration part. Look just above it and he posts the Ruby times at around 5m. Still, pretty drastic.
- macobo 13y agoThis problem has a quite elegant solution - Suppose you know the fair palindromes (is a palindrome and a root of a palindrome) of length 2*k. Then you can add either a single digit or double that to the center, and test if it's fair. This algorithm generates all the fair palindromes. https://gist.github.com/macobo/5430510 https://gist.github.com/macobo/5430510 By memory, there were under 50000 such palindromes in range 0..10^100.
- anonymoushn 13y agoThis is the real solution and is required for solving the second large.
- ClifReeder 13y agoTo clarify, the Go program (which took under a second to run) was doing the same processing as the full Ruby program that took 50 minutes to run.
- deleted 13y ago[deleted]
- KVFinn 13y agoOthers have asserted that they aren't doing the same processing and the GO program is not correct. https://news.ycombinator.com/item?id=5586152 https://news.ycombinator.com/item?id=5586152
- jff 13y agoGo is not an acronym Go is not an acronym Go is not an acronym See also: "ham" (amateur radio) is not an acronym