-
Notifications
You must be signed in to change notification settings - Fork 1
/
SolucaoElegante.java
54 lines (38 loc) · 1.27 KB
/
SolucaoElegante.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package solucaoElegante;
import java.util.Scanner;
public class SolucaoElegante {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int base = input.nextInt();
int expoente = input.nextInt();
System.out.println(potencia(base, expoente));
input.close();
}
/*
* Esta é a potencia recursiva completa, ela aceita expoentes negativos e lança exeções quando
* há indeterminação do tipo 0 elevado a 0 e divisão por 0
*/
public static double potencia(int base, int expoente) {
if (base == 0 && expoente == 0 ) { throw new IllegalArgumentException("indeterminação 0^0!");}
if (base == 0 && expoente < 0 ) { throw new IllegalArgumentException("indeterminação, divisão por zero!");}
if (base == 0) { return 0; }
if (expoente == 0) { return 1; }
if(ehNegativo(expoente)) {
double b = potencia(base, -expoente);
return 1 / b;
}
if (ehPar(expoente)) {
double baseElevadaAMetadeDoExpoente = potencia(base, expoente / 2);
return baseElevadaAMetadeDoExpoente * baseElevadaAMetadeDoExpoente;
}
else {
return potencia(base, expoente - 1) * base;
}
}
private static boolean ehPar(int numero) {
return numero % 2 == 0;
}
private static boolean ehNegativo(int numero) {
return numero < 0;
}
}