3 ms·
Hint: Gauss. Sum of numbers 1 to 100. Using Gauss's insight, Ruby can solve 10,000 times faster than a naive C solution. I solved this a while back, while hig
by danielharan 15y ago
Hint: Gauss. Sum of numbers 1 to 100.
Using Gauss's insight, Ruby can solve 10,000 times faster than a naive C solution.
I solved this a while back, while high on drugs my dentist gave me. Blog post is down, but code is here: http://refactormycode.com/codes/8-integer-puzzle http://refactormycode.com/codes/8-integer-puzzle
- lurker14 15y agoWhat of the magic numbers in this solution? ThousandRange: def child_values @thousands * 1_000_000 + 499500 end def child_sizes NumberWriter.write(@thousands * 1_000).size * 1_000 + 18440 end MillionRange: def child_values @millions * 1_000_000_000_000 + 499_999_500_000 end def child_sizes NumberWriter.write(@millions * 1_000_000).size * 1_000_000 + 44_872_000 end
- danielharan 15y agoThe size of the strings for that range of numbers. So, e.g. all of the strings starting with "twenty" will have that length of string (here, 6) * 10, plus the "one" in "twentyone", etc. The "one", "two", "three", etc have the same length whether they're preceded by "twenty" or "thirty". Account for the repeated strings "hundred", "thousand" or "million" and what follows them and you'll get the magic numbers above.