<p>Given an array <code>nums</code> of <strong>distinct</strong> positive integers, return <em>the number of tuples </em><code>(a, b, c, d)</code><em> such that </em><code>a * b = c * d</code><em> where </em><code>a</code><em>, </em><code>b</code><em>, </em><code>c</code><em>, and </em><code>d</code><em> are elements of </em><code>nums</code><em>, and </em><code>a != b != c != d</code><em>.</em></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [2,3,4,6]
<strong>Output:</strong> 8
<strong>Explanation:</strong> There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,4,5,10]
<strong>Output:</strong> 16
<strong>Explanation:</strong> There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
	<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
	<li>All elements in <code>nums</code> are <strong>distinct</strong>.</li>
</ul>

class Solution {
public:
    std::unordered_map<std::size_t, std::size_t> factorial_table;

    [[nodiscard]]
    std::size_t factorial_uncached(std::size_t n) {
        if (n <= 1) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }

    [[nodiscard]]
    std::size_t factorial(std::size_t n) {
        auto [it, didEmplace] = factorial_table.emplace(n, 1);

        if (didEmplace) {
            it->second = factorial_uncached(n);
        }

        return it->second;
    }



    int tupleSameProduct(vector<int>& nums) {
        std::map<std::size_t, std::size_t> counts;

        // Step 1: Count the number of unique pairs that have the same product.
        for (std::size_t i = 0; i < nums.size(); ++i) {
            for (std::size_t k = i + 1; k < nums.size(); ++k) {
                counts[nums[i] * nums[k]]++;
            }
        }

        auto pairs_per_group = [this] (std::size_t n) -> std::size_t {
            if (n <= 1) {
                return 0;
            }

            // This is the number of outer tuples you can make {A, B}.
            const auto tuple_pairs = factorial(n) / (factorial(n - 2));

            // This is the number of ways each outer tuple can be expanded.
            const auto permutations_per_tuple = 4;

            return tuple_pairs * permutations_per_tuple;
        };

        int acc = 0;
        for (const auto& [prod, count] : counts) {
            acc += pairs_per_group(count);
        }
        return acc;
    }
};

136800