编程之美---阶乘末尾有几个"零"?(C#实现)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
delegate long DoMath(long num);

static void Main(string[] args)
{
Program p = new Program();
p.GetFactorial(26);
DoMath d = new DoMath(p.HowManyZero);
d += p.HowManyZero2;
d(26);
Console.Read();
}

public long HowManyZero(long num) //第一种解法
{
long result = 0;
for (long i = 1; i <= num; i++)
{
long j = i;
while (j % 5 == 0)
{
result++; //检查每一个数可以分解因式出多少个5
j /= 5;
}
}

Console.WriteLine(result);
return result;
}

public long HowManyZero2(long num) //第二种
{
long ret = 0;
while (num != 0)
{
ret += num / 5; //可以被5整除,然后是25、125、625......
num /= 5;
}

Console.WriteLine(ret);
return ret;
}

public decimal GetFactorial(long num) //获得阶乘
{
decimal ret = 1;
for (long i = 1; i <= num; i++)
{
ret *= i;
}

Console.WriteLine(ret);
return ret;
}
}
}

书上只标了2颗星,我怎么觉得这么费劲….
PS:decimal都算不到30的阶乘啊……

具体讲解书上有

顺便复习一下delegate~~~~~~~