一个整型变量只能用来存贮较小的 N!的值,当 N 较大时,可将阶乘值中的 每一个数字放在一个一维数组的一个元素中。使用这方法,打印:
① N!的值;
② N!-M!(M>N);
③ N!+M!
[C#]
public const int max = 30;
public static int N,M;
public static void Main(String[] args)
{
Console.Write("Please input N:");
N = Convert.ToInt32(Console.ReadLine());
if (N < 1)
{
Console.WriteLine("输入有误!");
Console.ReadLine();
return;
}
Console.Write("Please input M:");
M = Convert.ToInt32(Console.ReadLine());
if (M <1 || M>=N)
{
Console.WriteLine("输入有误!");
Console.ReadLine();
return;
}
int[] a = Factorial(N);
int[] b = Factorial(M);
Console.WriteLine("N!="+Print(a));
Console.WriteLine("M!=" + Print(b));
Console.WriteLine("N!+M!=" + Print(FacAdd(a,b)));
Console.WriteLine("N!-M!=" + Print(FacSubtract(a,b)));
int x=Factorial(N,false);
int y=Factorial(M, false);
Console.WriteLine("N!={0}", x);
Console.WriteLine("M!={0}", y);
Console.WriteLine("N!+M!={0}", x+y);
Console.WriteLine("N!-M!={0}", x-y);
Console.ReadLine();
}
public static int Factorial(int n,bool flag)
{
if (n == 1)
return 1;
else
return n * Factorial(n - 1,false);
}
public static int[] Factorial(int n)
{
int[] fa = new int[max];
fa[0] = 1;
int r;
for (int i = 1; i <= n; i++)
{
r = 0;
for (int j = 0; j < max; j++)
{
fa[j] = fa[j] * i + r;
r = fa[j] / 10;
fa[j] %= 10;
}
}
return fa;
}
public static int[] FacAdd(int[] a, int[] b)
{
int tmmax = Math.Max(a.Length, b.Length);
int[] res = new int[tmmax];
int r=0;
for (int i = 0; i < tmmax; i++)
{
if(i<a.Length)
r += a[i];
if (i < b.Length)
r += b[i];
res[i] = r % 10;
r /= 10;
}
return res;
}
public static int[] FacSubtract(int[] a, int[] b)
{
int tmmax = Math.Max(a.Length, b.Length);
int[] res = new int[tmmax];
int r = 0;
for (int i = 0; i < tmmax; i++)
{
if (i < a.Length)
r += a[i];
if (i < b.Length)
r -= b[i];
if (r < 0)
{
res[i] = r + 10;
r = -1;
}
else
{
res[i] = r;
r = 0;
}
}
return res;
}
public static string Print(int[] fac)
{
int i = fac.Length-1;
string sfac = string.Empty;
while (i >= 0 && fac[i] == 0)
i--;
while (i >= 0)
sfac += Convert.ToString(fac[i--]).Trim();
return sfac;
}