I tried to initialize factorials from 1 to 1000 to an biginteger array and calculating the sum of the digits. Why this code showing java.lang.NullPointerException? I think everything was initialized correctly.
class Main {
public static void main(String[] args) {
BigInteger[] b = new BigInteger[1010];
int[] ara = new int[1010];
BigInteger c;
b[0] = BigInteger.ONE;
b[1] = BigInteger.ONE;
ara[0] = ara[1] = 1;
String s;
int l, sum;
for (int i = 2; i <= 1001; i++) {
c = b[i - 1];
b[i] = b[i].multiply(c);
s = b[i].toString();
l = s.length();
sum = 0;
for (int j = 0; j < l; j++) {
sum += Character.getNumericValue(s.charAt(j));
}
ara[i] = sum;
}
Problem :
b[i] = b[i].multiply(c);
And look at your b array which you initialised
b[0] = BigInteger.ONE;
b[1] = BigInteger.ONE;
And now look at the for loop
for (int i = 2; i <= 1001; i++) {
c = b[i - 1];
b[i] = b[i].multiply(c);
You have only 0,1 indexes. It will throw NPE for index 2.
You are trying loop on 1001 elements and there are only 2 elements inside your array. Fill the b array with zeros first.
Solution :
Change your for loop as below and keep everything same. It works.
for (int i = 2; i <= 1001; i++) {
b[i] = BigInteger.ONE;
c = b[i - 1];
b[i] = b[i].multiply(c);
s = b[i].toString();
The algorithm for factorial is to take some value n and multiply that n by n - 1 until the value 1 is arrived at. Your algorithm doesn't appear to do that (it generates ones). I think you wanted something like
int len = 1010;
BigInteger[] b = new BigInteger[len];
int[] ara = new int[len];
for (int i = 0; i < len; i++) {
// calculate factorial.
b[i] = BigInteger.valueOf(i + 1);
for (int j = i; j > 1; j--) {
b[i] = b[i].multiply(BigInteger.valueOf(j));
}
// now sum digits.
for (char ch : b[i].toString().toCharArray()) {
ara[i] += Character.getNumericValue(ch);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With