ACM解题报告--Just the Facts (浙大1222)

高精度算法求阶乘尾数
部署运行你感兴趣的模型镜像
Just the Facts

Time limit: 1 Seconds   Memory limit: 32768K  
Total Submit: 1052   Accepted Submit: 179  

The expression N!, read as "N factorial," denotes the product of the first N positive integers, where N is nonnegative. So, for example,

N N!
0 1
1 1
2 2
3 6
4 24
5 120
10 3628800

For this problem, you are to write a program that can compute the last non-zero digit of the factorial for N. For example, if your program is asked to compute the last nonzero digit of 5!, your program should produce "2" because 5! = 120, and 2 is the last nonzero digit of 120.


Input

Input to the program is a series of nonnegative integers, each on its own line with no other letters, digits or spaces. For each integer N, you should read the value and compute the last nonzero digit of N!.


Output

For each integer input, the program should print exactly one line of output containing the single last non-zero digit of N!.


Sample Input

1
2
26
125
3125
9999


Sample Output

1
2
4
8
2
8


Problem Source: South Central USA 1997  

该题与北大的1604类似,但是数据n可以达到10^300,用数组实现显然是不现实的,必须采用高精度算法。

代码如下:

#include <iostream>
#include <string>
using namespace std;

int data[5]={1,2,4,8,6};

int op(int b[],int k)
{
 int i,l=0;
 for(i=1;i<=k;i++)
  l=(b[i]+l*10)%4;
 if(!l)
  l=4;
 return data[l];
}

int compute(int a[],int n)
{
 int b[310],i,flag,l,k,x,t;
 flag=l=k=0;
 for(i=1;i<=n;i++)
 {
  x=a[i]+l*10;
  if(x/5)
   flag=1;
  if(flag)
   b[++k]=x/5;
  l=x%5;
 }
 x=1;
 if(!k)
 {
  for(i=1;i<=l;i++)
   x=x*i%10;
 }
 else
 {
  x=op(b,k)*compute(b,k)%10;
  t=(a[n]>=5?5:0);
  for(i=1;i<=l;i++)
   x=x*(i+t)%10;
 }
 return x;
}

int main()
{
 string s;
 while(cin>>s)
 {
  int a[310],i,n;
  n=s.length();
  for(i=0;i<n;i++)
   a[i+1]=s[i]-48;
  cout<<compute(a,n)<<endl;
 }
 return 0;
}

您可能感兴趣的与本文相关的镜像

ComfyUI

ComfyUI

AI应用
ComfyUI

ComfyUI是一款易于上手的工作流设计工具,具有以下特点:基于工作流节点设计,可视化工作流搭建,快速切换工作流,对显存占用小,速度快,支持多种插件,如ADetailer、Controlnet和AnimateDIFF等

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值