Your problem is that the numbers generated are too large to be saved in int
or in long
.
When you say:
// int
a = 1134903170;
b = 1836311903;
resultado = 2,971,215,073;
// long
a = 4660046610375530309;
b = 7540113804746346429;
resultado = 1.22001604151e+19; // Muy largo para mostrar
Both results are very large and do not fit within a int
or a long
.
Remember that:
width minimum maximum
SIGNED
byte: 8 bit -128 +127
short: 16 bit -32 768 +32 767
int: 32 bit -2 147 483 648 +2 147 483 647
long: 64 bit -9 223 372 036 854 775 808 +9 223 372 036 854 775 807
To solve your problem you need to use BigInteger . Here the Official Documentation: Class BigInteger .
Code:
public static void main(String[] args) {
BigInteger a = new BigInteger("1");
BigInteger b = new BigInteger("2");
BigInteger c = new BigInteger("0");
for (int i = 1; i <= 100; i++) {
c = a.add(b); // Método para la suma
a = b;
b = c;
System.out.println("[" + i + "] " + a);
}
}
With this, long numbers will be stored correctly and you will not have negative or poorly calculated numbers.
Greetings.