el2e10
el2e10

Reputation: 1558

Is this the correct to find the sum of even numbers in a Fibonacci series?

is this the correct way to find the sum of even numbers in a fibonacci series.I am getting correct answer while using small range.I am getting a negative value when using an int and a positive number while using long.

public class t {
    public static void main(String args[]){
      int i1=1,sum;
      int i2 = 2,temp;
      System.out.println(i1);
      System.out.println(i2);
      sum = i2;

      for(int i = 2; i<4000000; i++){
        //System.out.println(i1+i2);
        if( (i1+i2)%2 == 0 ){
           sum = sum+i1+i2;
        }
        temp = i1;
        i1 = i2;
        i2 = temp+i2;
      }

      System.out.println(sum);
  }
}

Upvotes: 0

Views: 75

Answers (2)

el2e10
el2e10

Reputation: 1558

Thanks for all the help guys i got the question wrong.The required program for the answer is this :

public class fibeven {
    public static void main(String args[]){
        int i1=1;
        int i2 = 2,temp;
    //System.out.println(i1);
    //System.out.println(i2);
        int sum = i2;
        while ((i1+i2)<4000000){
        //System.out.println(i1+i2);
            if((i1+i2)%2==0){
                sum = sum+i1+i2;
            }
            temp = i1;
            i1=i2;
            i2 = temp+i2;
        }
        System.out.println(sum);
    }
}

Upvotes: 1

Uday
Uday

Reputation: 1215

If you are wondering why you are getting a negative value when using int, it's because the value of i2 variable at the end of for loop in your code has reached the MAX value of (2^32)-1. Once it reaches the max value it goes into negative. Since the MAX of long is (2^64)-1, it won't overflow in your loop.

Upvotes: 1

Related Questions