Fibonacci Series in Java

Fibonacci series is a series of numbers written in such a way that each number (leaving first two numbers 0, 1) is generated from the sum of previous two numbers.

Ex: 0, 1, 1, 2, 3, 5, 8, 13, 21

Method 1: Simple but not optimal

package com.techstackjournal.java.basics;
public class FibonacciSeriesMethod1 {
	public static void main(String[] args) {
		int a, b, c, i, n;
		n = 10;
		a = 0;
		b = 1;
		i = 2;
		System.out.format("Printing %d Fibonacci numbers: ", n);
		while (i < n) {
			i++;
			c = a + b;
			a = b;
			b = c;
			System.out.format("%d ", a);
		}
	}
}

Method 2: Optimal

package com.techstackjournal.java.basics;
public class FibonacciSeriesMethod2 {
	public static void main(String[] args) {
		int a, b, i, n;
		n = 10;
		a = 0;
		b = 1;
		i = 2;
		System.out.format("Printing %d fibonacci numbers: ", n);
		if (n > 0) {
			while (i < n) {
				System.out.format("%d %d ", a, b);
				a = a + b;
				b = a + b;
				i = i + 2;
			}
			if (i == n) {
				System.out.format("%d %d ", a, b);
			} else {
				System.out.format("%d", a);
			}
		}
	}
}

References:

Wiki Page – Fibonacci Number

Leave a Comment