HELP: Factorials

Let's talk about algorithms!

Moderator: Board moderators

Post Reply
cOsMo
New poster
Posts: 8
Joined: Fri Dec 10, 2004 11:04 pm
Location: Split , Croatia

HELP: Factorials

Post by cOsMo »

I must find the last non zero digit of n!

Code: Select all

#include <cstdio>

int find_last(int x) {
	while (x%10==0) x/=10;
	return x%10;
}
int fact(int x) {
	int sol=1;
	for (int i=1;i<=x;i++)
		sol=find_last(find_last(i)*find_last(sol));
return sol;
}
int main(void)
{
	 int n;
	 scanf("%d",&n);
	 printf("%d\n",fact(n));
	 return 0;
}
I don't know what I did wrong...Plz help
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba »

Your algorithm is wrong. 14! = 87178291200, 15! = 1307674368000.
Dominik Michniewski
Guru
Posts: 834
Joined: Wed May 29, 2002 4:11 pm
Location: Wroclaw, Poland
Contact:

Post by Dominik Michniewski »

use the following algorithm
1. Factorize n!
2. reduce power of 2 by power of 5 (reducing trailing zeroes)
3. observe that last digit of 2^x is
- 2^0 = 1, 2^1=2,2^2=4,2^3=8,2^4=6,2^5=2,2^6=4 .... so pattern is 24862486.... so last digit of 2^x is last digit of 2^(x%4)
- make the same steps for 3^x, 7^x ...
- observe that multiplying by 17 is the same (for last digit) like multiplying by 7 ... and so on

Best regards
DM
If you really want to get Accepted, try to think about possible, and after that - about impossible ... and you'll get, what you want ....
Born from ashes - restarting counter of problems (800+ solved problems)
cOsMo
New poster
Posts: 8
Joined: Fri Dec 10, 2004 11:04 pm
Location: Split , Croatia

tnx

Post by cOsMo »

Thank you all. I totally misunderstood the problem.
Post Reply

Return to “Algorithms”