Euler Project # 2 Infinity?

I am trying to solve Euler Project # 2 , and I continue to receive the answer as "Infinity" or "NaN" (not a number) I tried to change the type of the number to int(initially Double), but it 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);
    }
}

Questions:

Each new member of the Fibonacci sequence is generated by adding the two previous members. Starting from 1 and 2, the first 10 members will be:

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

Considering the members in the Fibonacci sequence, whose values ​​do not exceed four million, we find the sum of the even members.

+5
source share
7 answers

4 000 000 x , 4 000 000.

+8

- : Java int Integer.MAX_VALUE (2147483647). , Integer.MIN_VALUE, . :

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));
    }
}

, , java.math.BigInteger:

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));
    }
}

. , . ,

+3

, . fibo(4000000) MAX_INT.

:, 4 000 000 , , 4000000.

, f< 4000000, , , i 4 000 000

+2

4 , , 4 , . , , , , , Integer.MAX_INT, , . , Integer.MAX_INT, , , int.

+1

GMP C. (, , n )...

0

long int.

, . , , /.

n i, 4 .

0

:

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

0

All Articles