The problem is in the function that calculates the factorial.
Notice that fatorial
starts with zero. If the number is, say, 2
, he enters the else
, and within the for
you multiply fatorial
for i
. But how fatorial
is zero, multiplying it by any number will result in zero. Then within the loop you are trying to make a division by zero, which gives error.
So actually the factorial should start at 1, not zero:
static double fatorial(int numero) {
double fatorial = 1;
for (int i = 2; i <= numero; i++) {
fatorial *= i;
}
return fatorial;
}
Notice you don’t even need the if
, because if the number is zero, it doesn’t enter the for
(since the condition i <= numero
will be false) and will be returned 1
.
And changed the kind of int
for double
, because the factor of 17 bursts the maximum size of a int
(which is 2147483647), and there occurs a overflow and the account goes wrong.
And the calculation is also wrong. By making a loop inside each other, actually you’re doing 100 / 0! + 100 / 1! + ... + 100 / 20! + 99 / 0! + 99 / 1! ...
. You only need to make one loop, and keep changing i
and j
at the same time:
double soma = 0;
for (int i = 100, j = 0; i >= 80; i--, j++) {
soma += i / fatorial(j);
System.out.printf("%d / %f + ", i, fatorial(j));
}
But in fact it does not need a method to calculate the factorial (unless it is requirement of exercise). For when you calculate, for example, 3!, you have already multiplied 2 and 3. In the next iteration, you will calculate 4! and you will have to multiply again 2 and 3, then multiply by 4.
In this case, it is better to keep the last calculated factorial and only multiply what is missing:
double soma = 0;
double denominador = 1;
for (int i = 100, j = 0; i >= 80; i--, j++) {
soma += i / denominador;
System.out.printf("%d / %f + ", i, denominador);
if (j > 0)
denominador *= (j + 1);
}
The problem is that the factorial cannot start with 0, it has to be with 1, because the multiplication by 0 gives 0. But it will give another problem of
int
, will have to use aBigInteger
, see https://answall.com/q/58533/101.– Maniero