USACO 3.2.1 – Factorials

the max N is 4,200, first truncate all right-most zeros whenever found. then recall the multiplication process, if you multiplied 4,200 by the previous factorial. then the right most digitl will be the result of mutlip. of 4,200 by the last digit of the previous factorial. and since every time you increase the digit index you add a right most zero. then only the last Log_10(4,200) digits should be kept.

#include <cstdio>

int main() {
	freopen("fact4.in", "r", stdin), freopen("fact4.out", "w", stdout);
	int N, f=1;
	scanf("%d", &N);
	for(int i=2; i<=N; f%=10000, i++){
		f*= i;
		while(f%10==0) f/=10;
	}
	printf("%d\n", f%10);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: