Question

How can the factorial of a factorial of a number be efficiently computed.
Example:For 3 => (3!)! = (6)! = 720
The brute force way would be to simply call factorial twice using a simple for loop but can it be done better.

for(i=1;i<=n;i++) 
   fact=fact*i; 

Edit: Need the result as ((n!)!)MOD 10^m, where m is an integer and 0<=m<=19

Was it helpful?

Solution

Note that result is 0 for n >=5 (5!!=120! has more than 19 zeros at the end), and result for smaller values it is easy to calculate.

OTHER TIPS

Since ab mod n ≣ (a mod n)(b mod n), you can use the brute force algorithm, dividing by 10m after each multiplication. If the product ever equals 0, you can stop.

here i am using PHP.I think It help You

<?php
  function double_factorial ($n)
    {
        if($n <= 1) 
        {
            return 1;
        }
        else 
        {
             $fat1=$n * factorial($n - 1);
            return $fat1 * factorial($fat1 - 1);
        }
    }
    echo double_factorial(3);

?>

1.For standard integer types

  • I agree with MBo
  • I would prefer table of precomputed values

2.For bigints

The following code has been tested and works very well.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication50
{
    class Program
    {
        static void Main(string[] args)
        {
            NumberManipulator manipulator = new NumberManipulator();
            Console.WriteLine("Factorial of six is :" + manipulator.factorial(16));
            Console.ReadLine();
        }
    }
class NumberManipulator
{
    public int factorial(int num)
    {
        int result=1;
        int b = 1;
        do
        {
            result = result * b;//fact has the value 1  as constant and fact into b will be save in fact to multiply again. 
            Console.WriteLine(result);
            b++;
        } while (num >= b);
        return result;
    }
  }
}
public class Factorial {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int input = scanner.nextInt();
    int result = Factorial(input);
    System.out.println(result);
    scanner.close();
}

private static int Factorial(int input) {
    int m = 1;
    if (input < 0) {
        return 0;
    } else if (input > 0) {
        m = input * Factorial(input - 1);
    }
    return m;
}

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top