From 56e887213bffa683cd89501c6726c6135b09b2cd Mon Sep 17 00:00:00 2001 From: shellhub Date: Wed, 23 Oct 2019 21:42:04 +0800 Subject: [PATCH 1/2] add pow --- Maths/Pow.java | 26 ++++++++++++++++++++++++++ Maths/PowRecursion.java | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 Maths/Pow.java create mode 100644 Maths/PowRecursion.java diff --git a/Maths/Pow.java b/Maths/Pow.java new file mode 100644 index 00000000..605e01d9 --- /dev/null +++ b/Maths/Pow.java @@ -0,0 +1,26 @@ +package maths; + +public class Pow { + public static void main(String[] args) { + assert pow(2, 0) == Math.pow(2, 0); + assert pow(0, 2) == Math.pow(0, 2); + assert pow(2, 10) == Math.pow(2, 10); + assert pow(10, 2) == Math.pow(10, 2); + } + + /** + * Returns the value of the first argument raised to the power of the + * second argument + * + * @param a the base. + * @param b the exponent. + * @return the value {@code a}{@code b}. + */ + public static long pow(int a, int b) { + long result = 1; + for (int i = 1; i <= b; i++) { + result *= a; + } + return result; + } +} diff --git a/Maths/PowRecursion.java b/Maths/PowRecursion.java new file mode 100644 index 00000000..673b8fde --- /dev/null +++ b/Maths/PowRecursion.java @@ -0,0 +1,26 @@ +package Maths; + +public class PowRecursion { + public static void main(String[] args) { + assert pow(2, 0) == Math.pow(2, 0); + assert pow(0, 2) == Math.pow(0, 2); + assert pow(2, 10) == Math.pow(2, 10); + assert pow(10, 2) == Math.pow(10, 2); + } + + /** + * Returns the value of the first argument raised to the power of the + * second argument + * + * @param a the base. + * @param b the exponent. + * @return the value {@code a}{@code b}. + */ + public static long pow(int a, int b) { + int result = 1; + for (int i = 1; i <= b; i++) { + result *= a; + } + return result; + } +} From d11b7347b650c225e31b1d46ec0f8800a8ce1fd9 Mon Sep 17 00:00:00 2001 From: shellhub Date: Thu, 24 Oct 2019 11:54:37 +0800 Subject: [PATCH 2/2] using recursion --- Maths/PowRecursion.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Maths/PowRecursion.java b/Maths/PowRecursion.java index 673b8fde..24354870 100644 --- a/Maths/PowRecursion.java +++ b/Maths/PowRecursion.java @@ -17,10 +17,10 @@ public class PowRecursion { * @return the value {@code a}{@code b}. */ public static long pow(int a, int b) { - int result = 1; - for (int i = 1; i <= b; i++) { - result *= a; + if (b == 0) { + return 1; + } else { + return a * pow(a, b - 1); } - return result; } }