技术开发 频道

字符串保存n的阶乘值

 【IT168技术文档】字符串保存n的阶乘值 收藏

view plaincopy to clipboardprint?

 /// 下面是一个用字符串保存100阶乘的例子。

 ///  Programmed by fired fish.

 using System;

 namespace Testf100

 {

 class Program

 {

 /// <summary>

 /// 应用程序的主入口点。

 /// </summary>

 [STAThread]

 static void Main()

 {

 test test1 = new test();

 /// 100是输入数,用来计算100的阶乘。

 string str = test1.f100(100);

 System.Console.WriteLine(str);

 }

 }

 public class test

 {

 /// 阶乘计算函数。

 /// 原理:每一次递归都将处理前一次递归返回的字符串。

 /// 将每一个数字字符转换成数字,再和n相乘,再加上低位进

 /// 得出和k,k再除10取余数,将余数转换成字符, 保存到char[]

 /// 中,然后k等于k/10 。

 ///

 public string f100(int n)

 {

 if (n <= 1)

 return "1";

 /// 其他情况

 /// 将每一个字符转换成数字,然后和n相乘

 string str = f100(n - 1);

 char[] chrList = new char[str.Length + 3];

 int k = 0;

 int i = 0;

 for (int j = str.Length - 1; j >= 0; j--)

 {

 int num = int.Parse(str[j].ToString());

 k += num * n;

 int mod = k % 10;

 chrList[i++] = Convert.ToChar(mod + '0');

 k /= 10;

 }

 while ((k >= 10) && (i <= chrList.Length - 1))

 {

 int mod = k % 10;

 chrList[i++] = Convert.ToChar(mod + '0');

 k /= 10;

 }

 if (k > 0 && i < chrList.Length - 1)

 chrList[i++] = Convert.ToChar(k + '0');

 Array.Reverse(chrList, 0, i);

 return new string(chrList, 0, i);

 }

 }

 }

 /// 使用n=100,结果为93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

 /// 使用n=10验证,结果为3628800

 查看原文地址

0
相关文章