求n!
程序员文章站
2024-03-15 15:45:11
...
/********************************************************
* 求n!
* (1)当n=0,1时,n!=1
* (2)当n>1时,n!=n(n-1)!
*********************************************************/
* 求n!
* (1)当n=0,1时,n!=1
* (2)当n>1时,n!=n(n-1)!
*********************************************************/
using System;
class Test
{
static void Main(string[] args)
{
Factorial f = new Factorial();
long a = f.F(4);
Console.Write(a);
Console.Read();
}
}
class Factorial
{
public long F(long n)
{
if (n < 0)
return -1;
if (n == 0 || n == 1)
return 1;
else
return n * F(n - 1);
}
}
/***********************************************************************
* 用数组实现n!
* n可以是百为数
************************************************************************/
using System;
class F
{
public F() { }
const int UNIT = 100;
static int count = 1;
static void Main(string[] args)
{
begin:
int a = Convert.ToInt32(Console.ReadLine());
Factorial(a);
Console.ReadLine();
goto begin;
}
public static void Factorial(int n)
{
int[] array = new int[100];
array[0] = 1;
count = 1;
while (n > 0)
{
Dohandle(array, n);
n--;
}
Console.WriteLine("Count = " + count);
Console.Write("阶乘计算结果 = ");
for (int i = count; i > -1; i--)
{
Console.Write(array[i].ToString("00"));
}
}
private static void Dohandle(int[] array, int n)
{
//每个数组元素存储2位
for (int i = count; i > -1; i--)
{
array[i] *= n;
if (array[i] > UNIT)
{
array[i + 1] += array[i] / UNIT;
array[i] = array[i] % UNIT;
if (i >= count)
{
count = i + 1;
}
}
}
}
}