File tree Expand file tree Collapse file tree 1 file changed +11
-8
lines changed Expand file tree Collapse file tree 1 file changed +11
-8
lines changed Original file line number Diff line number Diff line change @@ -19,13 +19,16 @@ public static void main(String[] args) { //main method
19
19
* @return the factorial of {@code n}
20
20
*/
21
21
public static long factorial (int n ) {
22
- if (n < 0 ) {
23
- throw new ArithmeticException ("n < 0" ); //Dont work with less than 0
24
- }
25
- long fac = 1 ;
26
- for (int i = 1 ; i <= n ; ++i ) {
27
- fac *= i ;
28
- }
29
- return fac ; //Return factorial
22
+ // Using recursion
23
+ try {
24
+ if (n == 0 ) {
25
+ return 1 ; // if n = 0, return factorial of n;
26
+ }else {
27
+ return n *factorial (n -1 ); // While N is greater than 0, call the function again, passing n-1 (Principle of factoring);
28
+ }
29
+ }catch (ArithmeticException e ) {
30
+ System .out .println ("Dont work with less than 0" );
31
+ }
32
+ return n ;
30
33
}
31
34
}
You can’t perform that action at this time.
0 commit comments