We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Problem with bigger factorial values
Page Index Toggle Pages: 1
Problem with bigger factorial values (Read 864 times)
Problem with bigger factorial values
Mar 23rd, 2009, 11:41pm
 
Hi forum,
I need to work with bigger factorials.
I already read about the problems with the big numbers.

This code would not work for integers bigger than 19, on a PC.

void draw() {
   int f = fact(20);
   println(f);
}

int fact(int n) {
 if (n <= 1) {
   return 1;
 }
 else {
   return n * fact(n-1);
 }
}


But I've found this link:
http://leepoint.net/notes-java/data/numbers/60factorial.html

I have no idea how to use the java.Math.BigInteger for my sketch - does anyone has an idea?
Re: Problem with bigger factorial values
Reply #1 - Mar 24th, 2009, 6:50am
 
The page you point to is good, showing that a recursive solution as you use is bad, and providing full code for calculating a factorial iteratively.

You can use the content of the main() function as is in your Processing sketch.
I wouldn't put that in draw(), though, unless you really need to compute that 60 times per second. setup() is a better place.
Re: Problem with bigger factorial values
Reply #2 - Mar 24th, 2009, 9:40am
 
Thank you PhiLho.

that was really easy... Still much to learn!

This is the code

import java.math.BigInteger;
void setup(){
 BigInteger n = BigInteger.ONE;
 for (int i=1; i<=20; i++) {
   n = n.multiply(BigInteger.valueOf(i));
   System.out.println(i + "! = " + n);
 }
}
Re: Problem with bigger factorial values
Reply #3 - Mar 24th, 2009, 10:33am
 
As said in the linked page, factorial is the "Hello World!" of recursive functions because it is so simple... and the worst example, because it is also trivial to do it in iterative fashion. Fibonacci is perhaps a better usage of recursiveness.

Note: Processing has a "native" println, no need for System.out.println.
Page Index Toggle Pages: 1