Project Euler #24: Lexicographic permutations

  • + 0 comments

    //C# using System; using System.Collections.Generic;

    class Program { const int mod = 1000000007;

    static long Fact(long n)
    {
        if (n <= 1)
            return 1;
    
        return Fact(n - 1) * n;
    }
    
    static void Solve()
    {
        long n = long.Parse(Console.ReadLine());
        n--;
        List<char> alpha = new List<char> { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm' };
        string ans = "";
    
        for (int i = 12; i >= 0; --i)
        {
            long factorial = Fact(i);
            long x = n / factorial;
    
            ans += alpha[(int)x];
            n -= factorial * x;
    
            alpha.RemoveAt((int)x);
        }
    
        Console.WriteLine(ans);
    }
    
    static void Main()
    {
        int t = int.Parse(Console.ReadLine());
    
        while (t-- > 0)
        {
            Solve();
        }
    }
    

    }