The Fibonacci series is a sequence where each number is the sum of the two preceding ones, typically starting with 0 and 1. In this article, we will explore how to find the sum of Fibonacci numbers up to a given number N using Java. We will provide code examples and explain the logic behind the implementation.
Note. If you're interested in learning how to print the Fibonacci series in Java using different methods, please feel free to check out my previous article here: https://www.csharp.com/article/print-fibonacci-series-in-java-using-different-methods/.
Understanding the Fibonacci Series
The Fibonacci series begins with:
The subsequent numbers are generated by adding the two previous numbers:
- 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
The formula for Sum of Fibonacci Numbers
To find the sum of Fibonacci numbers up to N, we can iterate through the series and add each number until we reach or exceed N.
Implementation Steps
- Initialize Variables: Start with the first two Fibonacci numbers (0 and 1).
- Iterate: Use a loop to generate Fibonacci numbers until they exceed N.
- Sum: Keep a running total of the sums of these Fibonacci numbers.
Code Example
Here’s a simple Java program that implements this logic:
import java.util.Scanner;
public class FibonacciSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number (N): ");
int N = scanner.nextInt();
int sum = fibonacciSum(N);
System.out.println("The sum of Fibonacci numbers up to " + N + " is: " + sum);
scanner.close();
}
public static int fibonacciSum(int N) {
if (N < 0) return 0; // Return 0 for negative input
int a = 0, b = 1; // First two Fibonacci numbers
int sum = a; // Initialize sum with the first term
while (b <= N) {
sum += b; // Add current term to sum
int nextTerm = a + b; // Calculate next term
a = b; // Move to next term
b = nextTerm; // Update current term
}
return sum;
}
}
Explanation of the Code
- Input Handling: The program prompts the user to enter a number N.
- Fibonacci Calculation
- The fibonacciSum method initializes two variables, a and b, to represent the first two terms of the Fibonacci series.
- It uses a while loop to calculate subsequent terms until b exceeds N.
- Each valid Fibonacci number is added to the sum.
- Output: Finally, it prints the total sum of Fibonacci numbers up to N.
Running the Program
To run this program:
- Save it as FibonacciSum.java.
- Compile it using:
javac FibonacciSum.java
-
Run it using
java FibonacciSum
Output
When you run the program and input N=30.
Conclusion
In this article, we demonstrated how to find the sum of Fibonacci numbers up to a specified number, N, in Java. By understanding the logic behind generating the Fibonacci sequence and summing its values, you can easily implement variations for different requirements. This foundational knowledge can be applied in various programming scenarios involving sequences and series calculations.