File tree Expand file tree Collapse file tree 1 file changed +20
-9
lines changed
week4/priority-queues/task3 Expand file tree Collapse file tree 1 file changed +20
-9
lines changed Original file line number Diff line number Diff line change 1- ### Taxicab numbers
2-
3- # A `taxicab` number is an integer that can be expressed as the sum of two cubes of positive integers in two different ways: `a^3 + b^3 = c^3 + d^3`.
4- # For example, `1729` is the smallest taxicab number: `9^3 + 10^3 = 1^3 + 12^3`.
5- # Design an algorithm to find all taxicab numbers with `a`, `b`, `c`, and `d` less than `n`.
6-
7- # - Version 1: Use time proportional to `(n^2)*log(n)` and space proportional to `n^2`.
8- # - Version 2: Use time proportional to `(n^2)*log(n)` and space proportional to `n`.
9-
101def baseline ( n )
112 arr = [ ]
123
@@ -26,4 +17,24 @@ def baseline(n)
2617 arr . sort . uniq
2718end
2819
20+ def solution ( n )
21+ # n
22+ numbers = ( 1 ...n ) . map { |i | i **3 }
23+
24+ # n^2
25+ h = { }
26+ numbers . each_with_index do |a , i |
27+ ( ( i + 1 ) ...( n - 1 ) ) . each do |j |
28+ b = numbers [ j ]
29+ s = a + b
30+ h [ s ] ||= [ ]
31+ h [ s ] << [ a , b ]
32+ end
33+ end
34+
35+ h = h . select { |k , v | v . size > 1 }
36+ h . keys
37+ end
38+
2939p baseline ( 30 )
40+ p solution ( 30 )
You can’t perform that action at this time.
0 commit comments