Reputation: 1834
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
Upvotes: 2
Views: 1560
Reputation: 37
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;
}
}
Upvotes: -1
Reputation: 16813
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;
}
}
}
Upvotes: 0
Reputation: 51863
1.For standard integer types
2.For bigints
Upvotes: 0
Reputation: 125
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);
?>
Upvotes: 0
Reputation: 531708
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.
Upvotes: 2
Reputation: 80232
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.
Upvotes: 7