Reputation: 1717
I was solving this problem6, I dont even know the answer but, when I finished I think that I will get Ok, but my answers fails, 7910956276398901303 this is my answer 1303, can you help me with this error, I dont understand what is wrong my logic , code??, Its just a simple power function
Corrected
this is the correct code
import java.math.BigDecimal;
public class Problema6 {
static BigDecimal sum = BigDecimal.valueOf(0);
static BigDecimal num = BigDecimal.valueOf(0);
public static void main(String args[]) {
int n = 2;
for (int i = 1; i <= 15; i++) {
sum = sum.add(power(i, n));
n++;
}
System.out.println(sum);
String number = sum.toString();
System.out.println(number.substring(number.length() - 4, number.length()));
}
public static BigDecimal power(int x, int y) {
num = BigDecimal.valueOf(x).pow(y).add(BigDecimal.valueOf(y).pow(x));
return num;
}
}
Upvotes: 0
Views: 451
Reputation: 5582
I think the problem is with using Math.pow(...)
. Switch to BigDecimal.pow(...)
to avoid overflows
Upvotes: 3