Project Euler #24: Lexicographic permutations

  • + 0 comments

    Python Solution

    We have 13! possible combinations of the string 'abcdefghijklm'. In it, there are 12! * 13 combinations, each of which has a, b, c, ... m in the beginning. In each of those combinations, there are 11! * 12 combinations, housing the leftover letters.

    def factorial(n):
        if n == 1:
            return 1
        
        return n * factorial(n - 1)
        
    permutations = [factorial(i) for i in range(12, 0, -1)]
    
    for _ in range(int(input())):
        N = int(input()) - 1
        ret = ''
        letters = list("abcdefghijklm")
        
        for i in permutations:
            q, N = divmod(N, i)
            ret += letters.pop(q)
            
        ret += letters[0]
            
        print(ret)