Ramanujan Fourth Problem (LeetCode)
Interesting that LC decided to post a problem that was mentioned by the great Ramanujan.
The problem is down below, but the anecdote (which became known as the "Taxicab Number") about this particular problem is the following: when Ramanujan was already very sick in London, his mentor and friend G.H. Hardy made him a visit at the hospital. When he got there, they started having a casual conversation.
Ramanujan then asked Hardy how did he get to the hospital, for which Hardy replied "took a cab number 1729, unfortunately that's not a very interesting number", for which Ramanujan said "oh no my dear friend, 1729 is actually a very interesting number; it is the smallest number that is the sum of two different cubes (1^3 + 12^3 and 9^3 + 10^3)".
No one knows how Ramanujan knew about that particular fact - as Hardy once said, "all numbers are Ramanujan's personal friends". This was only exhaustively proved in 1957 with the help of computers.
Problem description and my solution down below. Approach was to cache the cubes and then a two-pointers with pruning. Cheers, ACC.
Integers With Multiple Sum of Two Cubes - LeetCode
You are given an integer n.
An integer x is considered good if there exist at least two distinct pairs (a, b) such that:
aandbare positive integers.a <= bx = a3 + b3
Return an array containing all good integers less than or equal to n, sorted in ascending order.
Example 1:
Input: n = 4104
Output: [1729,4104]
Explanation:
Among integers less than or equal to 4104, the good integers are:
- 1729:
13 + 123 = 1729and93 + 103 = 1729. - 4104:
23 + 163 = 4104and93 + 153 = 4104.
Thus, the answer is [1729, 4104].
Example 2:
Input: n = 578
Output: []
Explanation:
There are no good integers less than or equal to 578, so the answer is an empty array.
Constraints:
1 <= n <= 109
public class Solution {
static private List cubes = new List();
public IList FindGoodIntegers(int n)
{
if (cubes.Count == 0)
{
for (int i = 1; i * i * i <= 1000000000; i++)
cubes.Add(i * i * i);
}
SortedSet sortedSet = new SortedSet();
HashSet visited = new HashSet();
for (int i = 0; i < cubes.Count && cubes[i] <= n; i++)
{
for (int j = i; j < cubes.Count && cubes[j] <= n; j++)
{
int sum = cubes[i] + cubes[j];
if (sum > n) break;
if (visited.Contains(sum))
{
if (!sortedSet.Contains(sum)) sortedSet.Add(sum);
}
else
{
visited.Add(sum);
}
}
}
return sortedSet.ToList();
}
}

Comments
Post a Comment