Java Fibonacci Sequence: Finding the Sum of Even-Valued Terms Under 4 Million

  • Context: Comp Sci 
  • Thread starter Thread starter Robben
  • Start date Start date
  • Tags Tags
    Java Sequence
Click For Summary

Discussion Overview

The discussion revolves around a programming problem related to generating Fibonacci numbers and calculating the sum of even-valued terms that do not exceed four million. Participants explore issues with the implementation of the Fibonacci sequence in Java, particularly focusing on data type limitations and algorithm correctness.

Discussion Character

  • Homework-related
  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant presents a code snippet for generating Fibonacci numbers and calculating the sum of even terms, but encounters a negative result when inputting 4,000,000.
  • Another participant suggests that the issue may stem from exceeding the limits of integer data types and recommends using long instead of int.
  • Some participants confirm that the code works for smaller numbers but fails for larger inputs, even after changing data types to long and double.
  • There is a suggestion that the problem statement might imply finding a shortcut formula for the sum of even-valued terms.
  • One participant emphasizes the importance of understanding the distinction between the 4 millionth term and the highest term that does not exceed four million, indicating that the series grows rapidly.
  • Another participant points out that the loop should check the value of Fibonacci terms rather than the index to ensure it does not exceed four million.
  • Some participants discuss the properties of Fibonacci numbers, noting that every third Fibonacci number is even and providing examples of Fibonacci numbers and their maximum values for different integer types.
  • A side note is made about calculating Fibonacci numbers for negative indices and an alternative method using only two local variables.

Areas of Agreement / Disagreement

Participants generally agree on the need to clarify the problem statement and the importance of data types in the implementation. However, there is no consensus on the best approach to resolve the coding issues or the interpretation of the problem requirements.

Contextual Notes

Participants note limitations related to data type sizes and the rapid growth of Fibonacci numbers, which may affect the implementation. There are unresolved questions regarding the correct handling of the loop conditions and the interpretation of the problem statement.

Who May Find This Useful

This discussion may be useful for individuals interested in programming challenges related to Fibonacci sequences, data type considerations in Java, and algorithm optimization techniques.

Robben
Messages
166
Reaction score
2

Homework Statement



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.

Homework Equations



None

The Attempt at a Solution



I am not sure what is wrong with my code? The code produces a negative number when I type in 4000000 into the fib method parameter.

Java:
public static void fib(int k) {
    
    int result = 0;
    int[] array = new int[k];
    array[0] = 1;
    array[1] = 2;
    
    for (int i = 2; i < k; i++) {
        array[i] = array[i - 2] + array[i - 1];      
    }
    
    for (int even: array) {
         
         if (even % 2 == 0) {
             result += even;
         }
    }        
    System.out.println(result);
}
 
Last edited:
Physics news on Phys.org
Does it work for smaller numbers? If so then your algorithm is correct but you are exceeding the limit of integers. Try long instead of int for all variables.
 
scientific601 said:
Does it work for smaller numbers? If so then your algorithm is correct but you are exceeding the limit of integers. Try long instead of int for all variables.

It does work for smaller numbers but for large numbers it doesn't. I tried with long and double and it still produces different negative numbers?
 
You sure? If result is also long... (I said all variables).

Also I wonder if "find the sum of the even-valued terms" meant you are to find some shortcut formula.
 
scientific601 said:
You sure? If result is also long... (I said all variables).

Also I wonder if "find the sum of the even-valued terms" meant you are to find some shortcut formula.

Yup, I changed all the int to long and the method produced a different negative number.
 
It may be in the System.out.println statement. Try using formatting and use ll for "long long" sized integers.
Something like
System.out.printf("%ll", result)
 
Robben said:
The code produces a negative number when I type in 4000000 into the fib method parameter.

You may want to re-read the problem statement:)). There is a VERY significant difference between the 4 millionth term in the Fibonacci Sequence and the highest term that does not exceed 4 million: so significant that using long or double can't possibly save you in the case of the former. Try adding a println to print the last term (array[k-1]) to see how quickly the series grows... compare for example k=10 ,20,30,40...can you imagine how large the 4 millionth term in the sequence must be?
 
  • Like
Likes   Reactions: Robben
You are correct. The OP and I did not read the problem statement carefully.
The problem statement does not ask to go to the 4 millionth term but the term that does not exceed 4 million.
So the loop limit should check the value of
Code:
array[i] = array[i - 2] + array[i - 1];
instead of the index.
 
  • Like
Likes   Reactions: Robben
Fibonacci numbers, fib(0) = 0, fib(1) = 1, fib(2) = 1, fib(3) = 2, fib(4) = 3, ...
max values for 32 bit signed, unsigned, and 64 bit signed, unsigned integers:

fib(46) = 1836311903 = hex 6D73E55F
fib(47) = 2971215073 = hex B11924E1

fib(92) = 7540113804746346429 = hex 68A3DD8E61ECCFBD
fib(93) = 12200160415121876738 = hex A94FAD42221F2702

every 3rd fibonacci number is even (since pattern is even+odd, odd+even, odd+odd)
fib(0) = 0
fib(3) = 2
fib(6) = 8
fib(9) = 34
fib(12) = 144
fib(15) = 610
fib(18) = 2584
 
Last edited:
  • Like
Likes   Reactions: Robben
  • #10
That's a good observation! Using that sequence according to other sources we only have to go as high as about fib(33) which is well below our integer limits. Anything beyond that and the terms are above 4,000,000 anyway.
 
  • #11
On a side note, Fibonacci for negative numbers can be determined by noting:

fib(i-2) = fib(i) - fib(i-1)

fib(6) = 8
fib(5) = 5
fib(4) = 3
fib(3) = 2
fib(2) = 1
fib(1) = 1
fib(0) = 0
fib(-1) = 1
fib(-2) = -1
fib(-3) = 2
fib(-4) = -3
fib(-5) = 5
fib(-6) = -8

You can also calculate fibonacci sequence using only two local variables:

Code:
unsigned int fib(unsigned int n)
{
unsigned int f0, f1;
    f0 = n & 1;         /* if n even, f0=0=fib(0), f1=1=fib(-1) */
    f1 = 1 - f0;        /* else       f1=0=fib(0), f0=1=fib(-1) */
    switch(n%2){
        do{
            f1 += f0;
          case 1:
            f0 += f1;
          case 0:
            continue;
        }while(0 <= (int)(n -= 2));
    }
    return f0;
}
 
  • #12
scientific601 said:
Does it work for smaller numbers? If so then your algorithm is correct but you are exceeding the limit of integers. Try long instead of int for all variables.
I'm more familiar with the sizes of types for C and C++ than with Java, but it seems likely to me that a long and an int are the same size (i.e., 32 bits).
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K