The problem is that this multiplication that adopts a factorial pattern will generate a very large, very large number. It does not fit in a int
, or even a long
, needs a BigInteger
to make it work, there’s this beautiful code. With a int
the value quickly exceeds the limit, and does not give error for reasons of performance, then the number that should be more than 2 billion becomes negative (this is how it works even, it reverses the signal because of the overflow), and being negative the whole calculation happens to be wrong.
Beyond this could not begin the for
with 0, after all the multiplication by 0 will be 0, and all the results will be contaminated, has to start with 1.
import java.math.*;
class ParImpar {
public BigInteger totali;
public BigInteger totalp;
public ParImpar(BigInteger totali, BigInteger totalp) {
this.totali = totali;
this.totalp = totalp;
}
public static void main(String[] args) {
new ParImpar(BigInteger.ZERO, BigInteger.ONE).parImpar();
}
public void parImpar() {
for (BigInteger i = BigInteger.ONE; i.compareTo(BigInteger.valueOf(100)) != 0; i = i.add(BigInteger.ONE)) {
if (i.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ZERO) != 0) totali = totali.add(i);
else totalp = totalp.multiply(i);
}
System.out.println("Total pares " + totalp);
System.out.println("Total impar " + totali);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Making a class just to do this I think a construction very bad.
Have you done the table test of your code? You tried thresh it? In the first iteration of
for
, the value ofi
is zero, and in doingtotalp = totalp * i
, the value oftotalp
becomes zero. Thereafter, any other multiplication (totalp = totalp * i
) will result in zero...– hkotsubo
Possible duplicate of Loop "for" counted odd number, even and average
– Ricardo Pontual
@hkotsubo yes, but I also tried to start the property at 1 and even then the result was the same
– Raul Oliveira
No matter the initial value, the problem is that in the first iteration of
for
, the value ofi
is zero, and thentotalp
becomes zero. And any other multiplication then made will result in zero... I suggest you follow the above links (table test and debug) and try to apply to your code, and you will see more clearly what is happening...– hkotsubo
@Rauloliveira is not the same problem, I edited, already put the solution
– Maniero
@hkotsubo the problem is not that, it seemed to be even.
– Maniero
@Maniero I did a quick test and it seemed to be just that. But if you say it’s something else, I’ll wait for your answer :-)
– hkotsubo
@hkotsubo can show working?
– Maniero
@Maniero Yeah, I was wrong about my quick test - maybe I was too fast - and I didn’t pay attention to the possibility of overflow... You’re right, the
for
starting at zero is only part of the problem...– hkotsubo
@hkotsubo the two of us :)
– Maniero