Swift version: modular inverse
Intuition\n Describe your first thoughts on how to solve this problem. \nGreat explanation please refer\nhttps://leetcode.com/problems/count-anagrams/solutions/
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGreat explanation please refer\nhttps://leetcode.com/problems/count-anagrams/solutions/2947111/c-solution-math-with-explanation-each-step-in-detail/?orderBy=most_votes\n\nAdd on reference for Fermat\'s little theorem\nhttps://en.wikipedia.org/wiki/Fermat%27s_little_theorem\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. catch the factorial result for reuse\n2.  combination formula all $$n!/a!*b!$$ when there are 0...a and 0...b same items\n2. modularMultiplication for handling multiply overflow product\n3. binaryExponentiation for quickly get power of number\n4. moduloInverse for deal with dividing the factorial for same items\n\n\n# Code\n```\nclass Solution {\n    let mod = Int(1e9+7)\n    func countAnagrams(_ s: String) -> Int {\n        var anagrams = [String: [Character: Int]]()\n        for word in s.split(separator: " ") {\n            var anagram = [Character: Int]()\n            word.forEach {\n                anagram[$0, default: 0] += 1\n            }\n            anagrams[String(word)] = anagram\n        }\n\n        var result = 1\n        for anagram in anagrams {\n            var permutation = factorial(anagram.key.count)\n            var devideFactorial = 1\n            for value in anagram.value.values {\n                guard value > 1 else {\n                    continue\n                }\n                // (a/b)%m != a%m / b%m -> use modular inverse for division\n                permutation = modularMultiplication(permutation, moduloInverse(factorial(value)))\n            }\n            result = modularMultiplication(result, permutation)\n        }\n        return result\n    }\n    \n    var factorials = [Int: Int]()\n    func factorial(_ n: Int) -> Int {\n        if let cache = factorials[n] {\n            return cache\n        }\n        guard n > 1 else {\n            return 1\n        }\n        let result = modularMultiplication(n, factorial(n-1))\n        factorials[n] = result\n        return result\n    }\n    \n    // n^-1 % m\n    func moduloInverse(_ n: Int) -> Int {\n        binaryExponentiation(n, mod-2) % mod\n    }\n    \n    // (a * b) % m\n    func modularMultiplication(_ a: Int, _ b: Int) -> Int {\n        (a % mod * b % mod) % mod\n    }\n    \n    // pow(a, b)\n    func binaryExponentiation(_ a: Int, _ b: Int) -> Int {\n        if b == 0 {\n            return 1\n        }\n        let result = binaryExponentiation(a, b/2)\n        if b % 2 == 1 {\n            return modularMultiplication(a, modularMultiplication(result, result))\n        } else {\n            return modularMultiplication(result, result)\n        }\n    }\n}\n```
['Swift']