If you type in 11
, that means contador1
will become as high as 22 (you will loop 11 times, every loop you first increment contador
, and contador1
is twice that, so, 22. In other words, you'll end up having to calculate 22!.
The int
type does not hold any arbitrary integer. It can only hold integers between -2^31 and +2^31-1. If you try to go beyond those bounds, it just loops around. Witness it in action:
int x = Integer.MAX_VALUE; // a constant representing 2^31-1.
int y = x + 1;
System.out.println(x);
System.out.println(y);
// Prints: 2147483647
// -2147483648
Where'd that minus come from? That's that whole 'loops around' thing. 22! is much lager than than this upper bound. Hence, your code doesn't work and it also explains why your algorithm tosses a negative number in there.
You could choose to use long
instead which can hold it, but long
, too, has limits - 2^63-1 to be precise. You could use double
which goes ever further (up to about 1e308
which is a lot more than 2^63), but doubles are not accurate and the lack of accuracy gets worse as you move further away from 0. Past 2^53 or so, the distance between 2 representable numbers in the double
range is more than 1
, meaning, +1
no longer does anything (all operations on double
values are rounded to the nearest representable double after every operation).
More generally trying to do 'math' on really large numbers is a non-trivial affair, and your basic +
and /
can no longer get the job done. Look up the API of BigDecimal
which guarantees you perfect accuracy at the cost of, naturally, performance. You could use that, and get perfect answers. Though it'll take a while.