Last Digit By Factorial Divide

来源:互联网 发布:程序员前景 编辑:程序博客网 时间:2024/06/06 02:00

需求:

We are given two numbers A and B such that B >= A. We need to compute the last digit of this resulting F such that F =B! / A! where 1 <= A, B <= 10^18 (A and B are very large)

样例

Given A = 2, B = 4, return 2A! = 2 and B! = 24, F = 24 / 2 = 12 --> last digit = 2Given A = 107, B = 109, return 2

分析:

已知F=B!/A!=B*(B-1)*(B-2)*...*(A+1),求F的个位数即求若干乘积结果的个位数。有两种思路:

1、求B到A+1累乘的结果,然后返回结果除以10的余数,即为个位数,但是显然不行,因为乘积太大,有可能超过运算界限

2、分析可知,两个数的乘积的个位数即两个数个位数乘积的个位数,所以求F的个位数,其实就是求B到A+1的个位数的乘积的个位数,初始化乘积mul=1,依次遍历B到A+1,依次乘以每个被遍历数的个位数,然后取其当前的个位数,最后返回mul

代码:

public class Solution {    /*     * @param A: the given number     * @param B: another number     * @return: the last digit of B! / A!      */    public int computeLastDigit(long A, long B) {        // write your code here        //从B到A+1遍历,乘积初始化是1,求每个数的个位数相乘的结果,每次的结果都求个位数        long mul = 1;        for(long i = B; i >= A+1; i--){            mul *= (i%10);            mul %= 10;                        if(mul == 0){                return 0;//如果当前乘积个位数是0,那么结果肯定是0            }        }                return (int)mul;    }}


原创粉丝点击