[BangPypers] Implementing a fast factorial function in python

Shashwat Anand anand.shashwat at gmail.com
Mon Sep 14 15:06:57 CEST 2009


How do we calculate last 5-digits of 10**12 ignoring trailing zeros. The
code i wrote works good until 10**8 and after that take ages.
The source of problem is Project Euler :
http://projecteuler.net/index.php?section=problems&id=160

The code is pasted here : http://paste.pocoo.org/show/139745/

 1 '''


  2 For any N, let f(N) be the last five digits before the trailing zeroes
in N!.
  3 For example,
  4
  5 9! = 362880 so f(9)=36288
  6 10! = 3628800 so f(10)=36288
  7 20! = 2432902008176640000 so f(20)=17664
  8
  9 Find f(1,000,000,000,000)
 10 '''
 11 def f(n):
 12     fac = 1
 13     i = 1
 14     #for i in range(1, n+1):
 15     while i < n + 1:
 16         fac = int(str(fac * i).strip('0')) % 100000
 17         i += 1
 18     return fac
 19
 20 print f(1000000000000)

PS. hope posting algorithmic doubts will not be considered spamming :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/bangpypers/attachments/20090914/c04eb6eb/attachment-0001.htm>


More information about the BangPypers mailing list