Merge pull request #1117 from shellhub/feature

add pow
This commit is contained in:
Yang Libin 2019-10-24 14:19:37 +08:00 committed by GitHub
commit 97cc89c7a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 0 deletions

26
Maths/Pow.java Normal file
View File

@ -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}<sup>{@code b}</sup>.
*/
public static long pow(int a, int b) {
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
return result;
}
}

26
Maths/PowRecursion.java Normal file
View File

@ -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}<sup>{@code b}</sup>.
*/
public static long pow(int a, int b) {
if (b == 0) {
return 1;
} else {
return a * pow(a, b - 1);
}
}
}