Shang Xian's first blog, noip elementary school question, find 0 number at the end of factorial, solution

@ [TOC] NOIP Elementary School
Insert picture description here

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
int main() {
	LL n, ans1, ans2;
	n = ans1 = ans2 = 0;
	scanf("%lld", &n);
	//找n以内有几个数的因数是五,一共有多少个五。(找到了一个5就可以和一个2配对,2*5=10,10有一个0) 
	for (LL i = 5; i <= n; i += 5) { 
		LL j = i;    
		//问:那为什么不找2呢? 答:2是一个偶数的必备因数,n以内的偶数肯定比5的倍数多 
		//问:不是一个数是5的倍数就行了吗? 答:不,如25,25=5*5,25的因数里有两个五,所以要用while循环来找 
		//问:那10呢?10不是有一个0吗? 答:10也有因数5呀,5可以和2组成一个10,那就不用再写一个循环来找10 
		while (j % 5 == 0  ) { 
			ans1++;					   
			j /= 5;
		}
	}
	//我们还要找n!!,如果n是奇数,如5!!=1*3*5,那么,这些数里面一个2的倍数也没有,所以5不能和2匹配
	if (n % 2 != 0) {  
		ans2 = 0;
	} else {
		for (LL i = 10; i <= n; i += 10) { // 如果n是偶数,2是有了,5却没有...但是,10有很多,一个10代表有一个0出现。 
			LL j = i;                      // 当然,10也有因数5,可如果找5的话,时间复杂度就上去了 => 错了。应该找5 
			while (j % 5 == 0  ) { // 找十 ==>>之前这里错了,因为没考虑有50*50的情况。 改成找5 
				ans2++;
				j /= 5;
			}
		}
	}
	printf("%lld %lld\n", ans1, ans2);
	return 0;
}
Posted 33 original articles · liked 0 · visits 167

Guess you like

Origin blog.csdn.net/weixin_42790071/article/details/104915598