zoukankan      html  css  js  c++  java
  • 【2001】关于N!的问题

    Time Limit: 3 second
    Memory Limit: 2 MB

    编写程序,计算n!以十进制数形式表示的数中最右边一个非零数字,并找出在它右边有几个零。

    例如:12!=1*2*3*4*5*...*12=479001600
    计算结果中,数字6是12!以十进制形式表示的数中最右边一个非零数字,它的右边有2个零。(程序应该适合于n为整型数的范围)

    Input

    输入文件中只一个数字,表示要计算的n的值(10<=n<=10000000)。

    Output

    输出两个数字,分为两行。
    第一行表示最右边的非零数字。
    第二行表示右边零的个数。

    Sample Input

    12
    

    Sample Output

    6
    2
    
     
    【题解】
    
    	5! = 1*2*3*4*5其中4 = 2*2 
    	-> 5!=1*2*2*2*3*5 
    	在阶乘中 0 由 2*5获得 而最右的非零数字则是除去这样的2和5配对后剩余的因子的乘积的个位数。一边乘一边取模就可以。
     
    【代码】
    #include <iostream>
    using namespace std;
    
    int n,i2,i5,rest,number0;
    //i2是2因子个数,i5是5因子个数,rest用于记录乘积的个位数 
    
    void input_data()
    {
    	cin >> n;	
    }
    
    void get_ans()
    {
    	rest=1;
    	i2=0;
    	i5=0;
    	for (int i=1;i<=n;i++) //対每个数都获取它的2因子个数和5因子个数,然后分解
    		{
    			int temp = i;
    			while ( temp % 2 == 0)
    				{
    					temp /=2;
    					i2++;
    				}
    			while ( temp % 5 == 0)
    				{
    					temp /=5;
    					i5++;	
    				}
    			rest = (rest * (temp % 10)) % 10;
    
    //做这些工作的时候可以一边乘
     		}
    	number0 = i5;
    	i2 -= i5;
     
    //直接减去5的因子个数是因为2的因子数一定大于5.
    	for (int i=1;i<=i2;i++)
     
    //把剩下的2也乘进去
    		rest=(rest*2) % 10;
    }	
    
    void output_ans()
    {
    	cout<< rest << endl;
    	cout<< number0;	
    }
    
    int main()
    {
    	input_data();
    	get_ans();
    	output_ans();
    	return 0;
    }
    

     
     
  • 相关阅读:
    3
    2
    1
    11
    12
    8888888888
    99999999999
    88888888888
    77777777
    10.23
  • 原文地址:https://www.cnblogs.com/AWCXV/p/7632513.html
Copyright © 2011-2022 走看看