Skip to main content
Participant
November 26, 2009
Question

Arbitrary-precision arithmetic in ColdFusion?

  • November 26, 2009
  • 3 replies
  • 765 views

I am trying to calculate the value of 100!.  I need all of the
digits.  ColdFusion gives me:

9.33262154445E+157

When what I want is:

93326215443944152681699238856266700490715968264381621
46859296389521759999322991560894146397615651828625369
7920827223758251185210916864000000000000000000000000

My code is:

function factorial(n)
{
         if (n == 1) return 1;
         return n * factorial(n - 1);

}

I tried using PrecisionEvaluate but can't seem to get what I need.

This topic has been closed for replies.

3 replies

BKBK
Community Expert
Community Expert
November 27, 2009

<!---

Calculate 100 factorial using exclusively numbers of
type BigDecimal. Then all significant figures count.

--->

<cfscript>

/* the double 1.0 as BigDecimal*/
factorial = createobject("java","java.math.BigDecimal").init(1.0);

/* 100 factorial = 1x2x3x ... x100, but then in BigDecimals.*/
for ( i = 2; i LTE 100; i = i+1) {
    iObj = createobject("java","java.math.BigDecimal").init(tostring(i));
    factorial = factorial.multiply(iObj);
}


/* Make Coldfusion store result as string, avoiding
truncation and scientific notation */
result = factorial.toPlainString();

// extract and display the integer part
writeoutput(listGetAt(result,1,"."));
</cfscript>

Inspiring
November 26, 2009

It's probably worth while reading up on the sizes of various numeric datatypes in Java, and how floating point numbers work.

Java (and, accordingly CF), is unlikely to be able to represent that number ot the accuracy you need it to.

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Long.html

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Double.html

http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigDecimal.html (which is what PrecisionEvaluate() uses)

http://en.wikipedia.org/wiki/Floating_point

To do what you need to do, you're going to have to write your own algorithm to represent numbers that long (as a string that you build up), or look around to see if someone else has already done it, and re-implement to fulfil your own requirements.

--

Adam

Inspiring
November 26, 2009

Try numberformat()