I have to make a method called calculate2 where I reduce the complexity of the method calculate1. But I did it in many different ways and it always gives me different results.
public static double calculo1(int n) {
double prod = 1.0;
double suma = 0.0;
for (int i = 0; i < n; i++) {
prod = 1.0;
for (int j = 1; j <= i; j++) {
prod = prod * j;
}
if (i % 2 == 0) {
suma += 1 / prod;
} else {
suma -= 1 / prod;
}
}
return suma;
}
public static double calculo2(int n) {
double prod = 1.0;
double suma = 0.0;
for (int i=0; i<n; i++)
{
prod = 1.0;
prod = prod * (i+1);
if (i % 2 == 0)
suma += 1 / prod;
else
suma -= 1 / prod;
}
return suma;
}
public static void main(String[] args) {
System.out.println("c1________________");
System.out.println(calculo1(9));
System.out.println(calculo1(2));
System.out.println(calculo1(3));
System.out.println(calculo1(12));
System.out.println("c2----------------");
System.out.println(calculo2(9));
System.out.println(calculo2(2));
System.out.println(calculo2(3));
System.out.println(calculo2(12));
}
Pay attention to what the following lines do:
They do the multiplication of all the integers from 1 to i. (
1 * 2 * 3 * ... * i
)While you replace it with:
More simply:
Because
prod
it is equal to 1 when the second line is executed. So 1 times any number is that same number.They are clearly not equivalent expressions. You are missing factors.
Take into account the original function. When you get to this part of the code:
When
i
it is 0,prod = 1
, wheni
it is 1,prod = 1
, wheni
it is 2,prod = 1*2
, wheni
it is 3,prod = 1*2*3
and so on.As you can see, in each iteration,
prod
it is worth the same as in the previous iteration but multiplied by one more number.In your simplified function you are on the right track. You just have to stop resetting
prod
to 1 every cycle and just multiply byi
.It happens that since it
i
starts at 0, the multiplication will give you 0 but you want it to be 1 at that moment. Well, just multiply byi
only ifi > 0
.The function looks like this: