From e5ad1f2ef0287426e4bef4fbc2aad6776d02bad5 Mon Sep 17 00:00:00 2001 From: Wendell Lucas <49886455+wendelllsc@users.noreply.github.com> Date: Tue, 17 Mar 2020 23:05:27 -0300 Subject: [PATCH] Using Try/catch and recursion Adding try/catch and recursion to optimize the code --- Maths/Factorial.java | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/Maths/Factorial.java b/Maths/Factorial.java index 3feb43356..61c82398b 100644 --- a/Maths/Factorial.java +++ b/Maths/Factorial.java @@ -16,13 +16,16 @@ public class Factorial { * @return the factorial of {@code n} */ public static long factorial(int n) { - if (n < 0) { - throw new ArithmeticException("n < 0"); //Dont work with less than 0 - } - long fac = 1; - for (int i = 1; i <= n; ++i) { - fac *= i; - } - return fac; //Return factorial + // Using recursion + try { + if (n == 0) { + return 1; // if n = 0, return factorial of n; + }else { + return n*factorial(n-1); // While N is greater than 0, call the function again, passing n-1 (Principle of factoring); + } + }catch (ArithmeticException e) { + System.out.println("Dont work with less than 0"); + } + return n; } }