Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Number of digits in n!

  1. Aug 9, 2006 #1
    I have to code a program in C that will give the correct number of digits of n! where n is upto 500.
    I thought this way:
    Get the value of log(n!) by using a for loop. (like log1 + log2 + log3.... upto logn, log is to the base 10). Now the final answer will be (int)sum + 1. If I give 500! factorial the answer comes out to be 1135 acc. to my program, but the answer given is 1133. Am I right?
  2. jcsd
  3. Aug 9, 2006 #2


    User Avatar
    Science Advisor

    I also get 1135.
  4. Aug 9, 2006 #3


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    500! =

    Code (Text):
    This has 1135 digits.

    - Warren
  5. Aug 10, 2006 #4
    I too verified with the teacher, the answer is 1135. But how in heaven did you calculate the value of 500!, chroot? What is the maximum precision of the calculator you used?
  6. Aug 10, 2006 #5


    User Avatar
    Homework Helper

    I think he used Methematica. It can handle most mathematical operations quite well.
    It can give you the evaluation of 500!, say, in less than 1 second. :rolleyes:
    The reason you got the wrong answer may be the rounding errors of the programme.
  7. Aug 10, 2006 #6


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Gagan A,

    I did indeed use Mathematica (VietDao29 probably recognized the tell-tale "\" characters at the end of each line in my output).

    It uses arbitrary-precision arithmetic, so the maximum precision is that afforded by the entire memory of my computer (2 GB on this one). 500! is computed, indeed, in the blink of an eye, and probably only uses a few kilobytes of memory.

    - Warren
  8. Aug 11, 2006 #7
    Yes Mathemathica really wotks great for calculations like this. But there are other good way's of doing it as well. I have in the past also did stuff like this with the Smalltalk programming language (it isn't very good for doing mathemathics but it does enable arbitrary-precision arithmetic) which was also qouit fast. I once also made a programm in C that could work with large integers (it used strings) but it wasn't veary fast.
  9. Aug 11, 2006 #8


    User Avatar
    Science Advisor
    Homework Helper

    It may be 'cheating' within the context of your course (if they want you to do this a certain way), but you might want to look up Stirling's series. You can calculate the log of gamma (and hence the factorial) to the necessary accuracy to find the number of digits without resorting to a summation.
  10. Aug 11, 2006 #9
    Python also supports arbitrary length integers:
    Code (Text):
    >>> def fac(a):
        if a==1: return a
        return a * fac(a-1)
    >>> len( str( fac( 500)))
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook