How to find all taxicab numbers less than N?

前端 未结 8 1519
攒了一身酷
攒了一身酷 2021-01-30 14:11

A taxicab number is an integer that can be expressed as the sum of two cubes of integers in two different ways: a^3+b^3 = c^3+d^3. Design an algorithm to find all t

8条回答
  •  孤独总比滥情好
    2021-01-30 14:44

    version1 uses List and sorting
    O(n^2*logn) time and O(n^2) space

        public static void Taxicab1(int n)
        {
            // O(n^2) time and O(n^2) space
            var list = new List();
            for (int i = 1; i <= n; i++)
            {
                for (int j = i; j <= n; j++)
                {
                    list.Add(i * i * i + j * j * j);
                }
            }
    
            // O(n^2*log(n^2)) time
            list.Sort();
    
            // O(n^2) time
            int prev = -1;
            foreach (var next in list)
            {
                if (prev == next)
                {
                    Console.WriteLine(prev);
                }
                prev = next;
            }
        }
    

    version2 uses HashSet
    O(n^2) time and O(n^2) space

        public static void Taxicab2(int n)
        {
            // O(n^2) time and O(n^2) space
            var set = new HashSet();
            for (int i = 1; i <= n; i++)
            {
                for (int j = i; j <= n; j++)
                {
                    int x = i * i * i + j * j * j;
                    if (!set.Add(x))
                    {
                        Console.WriteLine(x);
                    }
                }
            }
        }
    

    version3 uses min oriented Priority Queue
    O(n^2*logn) time and O(n) space

        public static void Taxicab3(int n)
        {
            // O(n) time and O(n) space
            var pq = new MinPQ();
            for (int i = 1; i <= n; i++)
            {
                pq.Push(new SumOfCubes(i, i));
            }
    
            // O(n^2*logn) time
            var sentinel = new SumOfCubes(0, 0);
            while (pq.Count > 0)
            {
                var current = pq.Pop();
    
                if (current.Result == sentinel.Result)
                    Console.WriteLine($"{sentinel.A}^3+{sentinel.B}^3 = {current.A}^3+{current.B}^3 = {current.Result}");
    
                if (current.B <= n)
                    pq.Push(new SumOfCubes(current.A, current.B + 1));
    
                sentinel = current;
            }
        }
    

    where SummOfCubes

    public class SumOfCubes : IComparable
    {
        public int A { get; private set; }
        public int B { get; private set; }
        public int Result { get; private set; }
    
        public SumOfCubes(int a, int b)
        {
            A = a;
            B = b;
            Result = a * a * a + b * b * b;
        }
    
        public int CompareTo(SumOfCubes other)
        {
            return Result.CompareTo(other.Result);
        }
    }
    

    github

提交回复
热议问题