Advertisement
aslv

Kth Factorial

Sep 15th, 2014
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System;
  2. using System.Numerics;
  3.  
  4. namespace KthFactorial
  5. {
  6.     class RecursiveSolution
  7.     {
  8.         static void Main()
  9.         {
  10.             Console.Write("n = ");
  11.             int n = int.Parse(Console.ReadLine());
  12.             Console.Write("k = ");
  13.             int k = int.Parse(Console.ReadLine());
  14.             BigInteger result = CalculateKthFactorial(n, k);
  15.             Console.WriteLine("The {0}-th factorial of {1} is {2}", k, n, result);
  16.         }
  17.  
  18.         /// <summary>
  19.         /// Finds the kth factorial of n.
  20.         /// The idea is that kth factorial = n^k * (n-1)^k * (n-2)^k * ... * 1
  21.         /// </summary>
  22.         /// <returns>Recursive call or 1.</returns>
  23.         private static BigInteger CalculateKthFactorial(int n, int k)
  24.         {
  25.             if (n <= 1)
  26.             {
  27.                 return 1;
  28.             }
  29.             return RaiseToThePowerOf(n, k) * CalculateKthFactorial(n - 1, k);
  30.         }
  31.  
  32.         /// <summary>
  33.         /// Raise a to the power of b. Does the same as Math.Pow(a, b), but it's faster because b is integer.
  34.         /// </summary>
  35.         /// <returns>a^b</returns>
  36.         private static BigInteger RaiseToThePowerOf(BigInteger a, int b)
  37.         {
  38.             BigInteger result = a;
  39.             for (int i = 1; i < b; i++)
  40.             {
  41.                 result *= a;
  42.             }
  43.             return result;
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement