Dan299
Dan299

Reputation: 165

Java - Trying to generate factorials

I'm making a calculator, and am adding a few more complicated buttons. The one I can't get my head around is factorial. I know what it is, but can't seem to make it. When I look at other people's questions, the code - for me anyway - doesn't work (Btw this is not a homework question). Here is the bit of code around where the algorithm (is that the word for it?) for the factorial:

} else if (oper.equals("shriek")) {

                resultm.setText("" + answer);
                resultl.setText("");
                resultr.setText("");
                oper = "";
                currentNuml = "";
                currentNumr = "";
            }

NB: The gap between

} else if (oper.equals("shriek")) {

and

resultm.setText("" + answer);

is where the algorithm would go. Thanks, any help would be appreciated!

Upvotes: 2

Views: 690

Answers (1)

cjds
cjds

Reputation: 8426

Two variants for creating a factorial would be a recursive and non-recursive method.

The basic logic of a factorial is 5! = 5*4*3*2*1

So that should be simple to implement with a loop (non-recursive). Just keep multiplying the number with the loop number to generate loop number

int fact(int no){
   int result=1;
   for (int i=1;i<no;i++)result*=i;
   return result;
}

The second is a recursive algorithm. This means calling the function from within itself.

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

This will work like so.

For example fact(3)

no=3 Go to else return 3*fact(2)
    no=2 Go to else return 2* fact(1)
                 no=1 return 1
    no=2 return 2*1 => 2
no=3 Return 3*2 => 6

Hope this helped you understand

Upvotes: 1

Related Questions