Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Numerics;
- namespace KthFactorial
- {
- class RecursiveSolution
- {
- static void Main()
- {
- Console.Write("n = ");
- int n = int.Parse(Console.ReadLine());
- Console.Write("k = ");
- int k = int.Parse(Console.ReadLine());
- BigInteger result = CalculateKthFactorial(n, k);
- Console.WriteLine("The {0}-th factorial of {1} is {2}", k, n, result);
- }
- /// <summary>
- /// Finds the kth factorial of n.
- /// The idea is that kth factorial = n^k * (n-1)^k * (n-2)^k * ... * 1
- /// </summary>
- /// <returns>Recursive call or 1.</returns>
- private static BigInteger CalculateKthFactorial(int n, int k)
- {
- if (n <= 1)
- {
- return 1;
- }
- return RaiseToThePowerOf(n, k) * CalculateKthFactorial(n - 1, k);
- }
- /// <summary>
- /// Raise a to the power of b. Does the same as Math.Pow(a, b), but it's faster because b is integer.
- /// </summary>
- /// <returns>a^b</returns>
- private static BigInteger RaiseToThePowerOf(BigInteger a, int b)
- {
- BigInteger result = a;
- for (int i = 1; i < b; i++)
- {
- result *= a;
- }
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement