UVA - 568 Just the Facts

来源:互联网 发布:javascript 是否是数组 编辑:程序博客网 时间:2024/06/09 23:21

题目大意:求阶乘的最后一位非零数字。

解题思路:一开始想保留最后一位非零数字往下乘,发现因为进位后来会出错。总之想办法降低数据大小,因为要抛弃末尾的 0,即因子中含一对 2 和 5 (2×5=10)可以相互抵消,显然 2 比 5 多,最后乘上多出的个数的 2 就行。

#include<iostream> #include<cstdio>#include<string.h>#include<stdlib.h>#include<cmath>using namespace std;int main() {    int n;    while(scanf("%d", &n) != EOF) {        int ans = 1;        int a = 0, b = 0;        for (int i = 2; i <= n; i++) {            int j = i;            while (j%2 == 0) {                a++;                j /= 2;            }            while (j%5 == 0) {                b++;                j /= 5;            }            ans = ans * j % 10;        }        for (int i = 0; i < a - b; i++)            ans = ans * 2 % 10;        printf("%5d -> %d\n", n, ans);    }    return 0; }
0 0
原创粉丝点击