diff --git a/src/main/java/Challenges.java b/src/main/java/Challenges.java index b5acedd..24d835f 100644 --- a/src/main/java/Challenges.java +++ b/src/main/java/Challenges.java @@ -64,8 +64,7 @@ public String[] circularArray(int index) { System.arraycopy(COUNTRY_NAMES, index, tempArray, 0, numberOfElementsToCopy); System.arraycopy(COUNTRY_NAMES, 0, tempArray, numberOfElementsToCopy, COUNTRY_NAMES.length - numberOfElementsToCopy); - COUNTRY_NAMES = tempArray.clone(); - return COUNTRY_NAMES; + return tempArray.clone(); } ; @@ -91,17 +90,18 @@ public String[] circularArray(int index) { ***** */ public String ownPower(int number, int lastDigits) { - BigInteger powResult = BigInteger.ZERO; + BigInteger moduloNumber = BigInteger.TEN.pow(lastDigits); + BigInteger moduloAddition = BigInteger.ZERO; for (int i = 1; i <= number; i++) { - BigInteger powNumber = new BigInteger(String.valueOf(i)).pow(i); + BigInteger resultModuloPow = BigInteger.valueOf(i).modPow(BigInteger.valueOf(i), moduloNumber); - powResult = powResult.add(powNumber); + moduloAddition = moduloAddition.add(resultModuloPow).mod(moduloNumber); } - String result = String.valueOf(powResult); + String result = String.valueOf(moduloAddition); - return result.substring(result.length() - lastDigits); + return "0".repeat(lastDigits - result.length()).concat(result); } ; @@ -125,17 +125,15 @@ A factorial (x!) means x! * (x - 1)... * 3 * 2 * 1. public Integer digitSum(int n) { BigInteger totalFactorial = BigInteger.ONE; + BigInteger sum = BigInteger.ZERO; for (int i = n; i >= 1; i--) { totalFactorial = totalFactorial.multiply(BigInteger.valueOf(i)); } - char[] digits = String.valueOf(totalFactorial).toCharArray(); - - BigDecimal sum = BigDecimal.ZERO; - - for (char c : digits) { - sum = sum.add(new BigDecimal(String.valueOf(c))); + while (totalFactorial.compareTo(BigInteger.ZERO) > 0) { + sum = sum.add(totalFactorial.mod(BigInteger.TEN)); + totalFactorial = totalFactorial.divide(BigInteger.TEN); } return sum.intValue();