码迷,mamicode.com
首页 > 其他好文 > 详细

Factorial

时间:2015-05-10 09:59:21      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:算法   c++   

Factorial
     
 
时间限制:1秒    内存限制:256兆
题目描述

     Many years later, Alice grow up and she become a high-school student.One day she learned factorial on math class. The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive.For example, 4! = 1 * 2 * 3 * 4 = 24, Likewise, 5! = 1 * 2 * 3 * 4 * 5 = 120.

    Alice found that the factorial quickly becomes very large, and she want to find the rightmost non-zero digit of N!.
输入格式

 There are T(1 <= T <= 50) test cases. For each test case, A single positive integer N no larger than 10000 and no smaller than 1. 

输出格式

 Each test case a single line containing a single digit: the right most non-zero digit of N!.

样例输入
4
4
5
6
7
样例输出
4
2
2
4

这题如果单纯的用递归或直接阶乘遇到比较大的数据时,肯定超时,可以先把前10个数据枚举出来,比10大的再讨论。尾数为零不外乎都是尾数为偶数和尾数为5的数相乘得到的,定义F(n)为所要求的数,G(n)为1,2…n中将5的倍数的数换成1后的各项乘积(如:G(15)=1*2*3*4*1*6*7*8*9*1*11*12*13*14*1)(G(n)%10必不为0)。只要把符合这个规律的数对破坏即可。不妨令其中尾数为5的数先看作1,定义F(n)为所要求的数,G(n)为1,2…n中将5的倍数的数换成1后的各项乘积(如:G(15)=1*2*3*4*1*6*7*8*9*1*11*12*13*14*1)(G(n)%10必不为0)。则n!=(n/5)!*5^(n/5)*G(n),F(n)=F(n/5)*[5^(n/5)*G(n)%10],这可用递归处理,另外观察到5^(n/5)*G(n)%10=G(n)/2^(n/5)%10,这里G(n)%10(n>=10)其实是个周期为10的周期序列(程序中的table),G(n)/2^(n/5)必为偶数,这样得到一种特殊除法:8/2=4,4/2=2,2/2=6,6/2=8…,这样G(n)/[2^(n/5)]%10只与G(n)%10和(n/5)%4有关。而G(n)%10=table[n%10],n/5%4=n/5%100%4(%100好算,就是最后两位数字)。


Factorial

标签:算法   c++   

原文地址:http://blog.csdn.net/a576699534/article/details/45603023

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!