• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer
  • Home
  • Java Tutorial
  • Java Posts
  • Node.js
  • Spring Core
  • Algorithms
  • Docker
  • Blogging
  • Misc
Tech Stack Journal

Tech Stack Journal

Fibonacci Series in Java

August 22, 2019 by Admin Leave a Comment

Contents

  • 1 Method 1: Simple but not optimal
  • 2 Method 2: Optimal
    • 2.1 References:

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

Filed Under: Java

Previous Post: « Check Leap Year in Java
Next Post: Command-line arguments in Java »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *


Primary Sidebar

More to See

Arrays.asList in Java Examples

February 21, 2021 By Admin

[Solved] Why List.add throws UnsupportedOperationException in Java?

February 20, 2021 By Admin

Secondary Sidebar

Categories

  • Algorithms
  • Blogging
  • Docker
  • Java
  • Misc
  • Node.js
  • Spring Core
  • Windows

Archives

  • February 2021 (6)
  • January 2021 (1)
  • December 2020 (1)
  • September 2020 (2)
  • August 2020 (5)
  • July 2020 (4)
  • June 2020 (1)
  • May 2020 (4)
  • April 2020 (22)
  • November 2019 (3)
  • September 2019 (2)
  • August 2019 (6)

Footer

Navigation

  • Home
  • Java Tutorial
  • Java Posts
  • Node.js
  • Spring Core
  • Algorithms
  • Docker
  • Blogging
  • Misc

Recent

  • How to Make File Explorer Open to This PC instead of Quick Access in Windows 10
  • Arrays.asList in Java Examples
  • [Solved] Why List.add throws UnsupportedOperationException in Java?
  • How to Convert an Array to List in Java?
  • How Many Spaces in a Tab?

Search

Copyright © 2021 · Tech Stack Journal · Log in