Any type of Java overflow?

0

was doing the problem # 2 Project Euler and suddenly notice that when the numerical quantities were high negative numbers were positive and positive, in C ++ I also had the same, someone knows why this is given?

 public static void main(String[] args) 
{

    //   c=a+b;
   int a=1,b=2,c=0;
   for(int i=1;i<=100;i++)
   {

   c=a+b;
   a=b;
   b=c;

       System.out.println(c);

   }


}

    
asked by Javier 29.05.2018 в 19:00
source

1 answer

1

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.

    
answered by 29.05.2018 / 19:36
source