5

I am trying to solve Euler's Project #2 and I keep getting the answer as "Infinity" or "NaN" (Not a number) I tried changing the type of number to a int (originally Double), but that didn't fix anything just gave me the answer "-1833689714"

public class Pro {
    static int g = 1;
    static int n, f = 0;
    public static void main(String args[]) {
        for (int i = 0; i <= 4000000; i++) {
            f = f + g;
            g = f - g;
            if (f % 2 == 0) {
                n += f;
            }
        }
        System.out.println("Answer: " + n);
    }
}

The questions is:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Spencer H
  • 450
  • 1
  • 6
  • 17
  • you might also want to check the BigInteger class: http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html – santiagozky Jan 19 '12 at 21:11

7 Answers7

8

You are considering the first 4,000,000 terms of the Fibonacci sequence instead of the first x terms which do not exceed 4,000,000.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
3

Your problem is an integer overflow: in Java, an int variable is limited to Integer.MAX_VALUE (2147483647). If you exceed this value in a computation, you overflow to Integer.MIN_VALUE, the smallest negative value. See:

public class IntegerOverflow {
    public static void main(String[] args) {
        int i = Integer.MAX_VALUE;
        System.out.println("i = Integer.MAX_VALUE: " + i);
        System.out.println("i + 1: " + (i + 1));
        System.out.println("i + 2: " + (i + 2));
    }
}

To avoid overflow problems, perform your computation with arbitrary-precision integers, provided by the java.math.BigInteger class:

import java.math.BigInteger;

public class BigIntegerExample {
    public static void main(String[] args) {
        BigInteger b = BigInteger.valueOf(Long.MAX_VALUE);
        System.out.println("b = Long.MAX_VALUE: " + b);
        System.out.println("b**2: " + b.multiply(b));
        System.out.println("b**3: " + b.pow(3));
        System.out.println("b**10: " + b.pow(10));
    }
}

Note: As you did not ask for help with the problem itself, I am just answering the question. Hope this helps

Danilo Piazzalunga
  • 7,590
  • 5
  • 49
  • 75
2

You are probably encountering an overflow. fibo(4000000) is way above MAX_INT.

Note: that you are not asked to find the sum even numbers in the 4,000,000 first numbers, but to find the sum of even elements which their value is not over 4,000,000.

You should check if f< 4000000 and if not, break, and not wait to i reach 4,000,000

amit
  • 175,853
  • 27
  • 231
  • 333
1

You are checking the first 4 million fibonacci, you need to only check terms until a fibonnaci term is greater than 4 million then stop. The reason you are getting negative numbers is that you are eventually getting fibonacci terms which are greater than Integer.MAX_INT, at which point you overflow and start getting negative numbers, which you are adding to your total. If you aren't positive whether or not the eventual answer is going to exceed Integer.MAX_INT, you should be using a long as your accumulator instead of an int.

stew
  • 11,276
  • 36
  • 49
0

This is how I got the answer:

def fib():
        x,y = 0,1
        while True:
            yield x
            x,y = y, x+y

def even(seq):
    for number in seq:
        if not number % 2:
            yield number

def under_a_million(seq):
    for number in seq:
        if number > 4000000:
            break
        yield number   

print sum(even(under_a_million(fib())))

-M1K3

seamonkey8
  • 17
  • 5
0

Use GMP to handle big numbers in C. And a little bit of thinking before does not hurt either (like how often is there an odd number versus even, what is the sum of the first n elements of Fibonacci sequence)...

Matthieu
  • 16,103
  • 10
  • 59
  • 86
  • 1
    This is not `C`, java has its native `BigInteger` class. Also, for this question `long` is more then enough. – amit Jan 19 '12 at 21:14
  • Using `long` may be more than enough, but `BigInteger` is preferred for high-precision calculations: http://docs.oracle.com/javase/tutorial/java/data/numberclasses.html – Danilo Piazzalunga Jan 19 '12 at 21:42
  • @DaniloPiazzalunga But for this problem you don't need high-precision calculations. Everything is **comfortably** done int `int` range. – Daniel Fischer Jan 19 '12 at 23:36
0

You can use long instead of int.

Every third expression is even, so you only need to evaluate every third value. This is slighly faster because it loops less times and you don't have to test for even/odd.

You only need to n not the i which is less than 4 million.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130