why my for returns a negative number if it's the sum of the previous numbers?

Viewed 33
    class Main {

public static long soma(int num){
  if (num > 10){
    return 0;
  }else{
    return num + soma(num+1);
  }
}
  
  public static void main(String[] args) {

    int vetor[] = new int[4000000];//creates an array to store fibonacci's values;
    vetor[0] = 1;
    vetor[1] = 2;
    int vet[] = new int[3000000];//creates an array to store even fibonacci's values;
    int n = 0;
    int valor = 0;

    for (int i = 0; i < 3999998; i++){
    int z = vetor[i];
    int y = vetor[i+1];
    int a = y+z;
    vetor[i+2] = a;
    } // fills the array by summing i + (i+1);

    for(int i = 0; i < 3000000; i++){
      if(vetor[i] % 2 == 0){
        valor = vetor[i];
        vet[n] = valor;
        n++;
      }//it fills the array of even fibonacci values using "for" to run all the array and selecting the values that % 2 results in 0; 
  }

    /**int resultado = soma(vetor[0]);
    System.out.println(resultado);**/

    System.out.println(vetor[0]);
    System.out.println(vetor[1]);
    System.out.println(vetor[2]);

    System.out.println("**************-**************");

    
    System.out.println(vetor[999]);
    System.out.println(vetor[1000]);
    System.out.println(vetor[1001]);

        System.out.println("**************-**************");


    System.out.println(vetor[250000]);
    System.out.println(vetor[250001]);
    System.out.println(vetor[250002]);

            System.out.println("**************-**************");

    System.out.println(vetor[1000000]);
    System.out.println(vetor[1000001]);
    System.out.println(vetor[1000002]);

}
 }

I'm trying to create an array with the fibonacci sequence but when I print it, the firsts ones are okay the latest are giving me some random negative numbers:

results

this code is supposed to make 2 arrays one of the fibonacci values of 0 up to 4 million and other array with only the even values of the first fibonacci array.

open to any advices and critics :)

1 Answers

The int limit in Java is less than the amount of numbers you're trying to generate, maybe this is causing it? try a long and see if that helps?

Edit: as pointed out by others, Long will overflow too because of the Fibonacci sequence's exponential growth. You'll need a BigInt for this

Related