From 12b86774ad06857051e687fe85521de1fd29c70f Mon Sep 17 00:00:00 2001 From: Deepak Date: Mon, 2 Oct 2017 12:53:43 +0530 Subject: [PATCH 1/3] add FibToN print all fibonacci till N in O(n) --- Misc/FibToN | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Misc/FibToN diff --git a/Misc/FibToN b/Misc/FibToN new file mode 100644 index 000000000..4d002b8f4 --- /dev/null +++ b/Misc/FibToN @@ -0,0 +1,21 @@ +import java.util.Scanner; + +public class FibToN { + + public static void main(String[] args) { + Scanner scn = new Scanner(System.in); + + int n = scn.nextInt(); + + int fn = 0, sn = 1; + + while(fn <= n){ + System.out.println(fn); + + int next = fn + sn; + fn = sn; + sn = next; + } + } + +} From 0afa2da3cef1778d88d24645cdf6009519846131 Mon Sep 17 00:00:00 2001 From: Deepak Date: Tue, 3 Oct 2017 08:32:14 +0530 Subject: [PATCH 2/3] rename .java extension added --- Misc/{FibToN => FibToN.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Misc/{FibToN => FibToN.java} (100%) diff --git a/Misc/FibToN b/Misc/FibToN.java similarity index 100% rename from Misc/FibToN rename to Misc/FibToN.java From 9b4ae39291b63cb465748406e34b5de241beaf39 Mon Sep 17 00:00:00 2001 From: Deepak Date: Tue, 3 Oct 2017 13:25:06 +0530 Subject: [PATCH 3/3] updated added comments and changed variable names for better understanding --- Misc/FibToN.java | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/Misc/FibToN.java b/Misc/FibToN.java index 4d002b8f4..e7b7a9a23 100644 --- a/Misc/FibToN.java +++ b/Misc/FibToN.java @@ -3,18 +3,21 @@ import java.util.Scanner; public class FibToN { public static void main(String[] args) { + //take input Scanner scn = new Scanner(System.in); + int N = scn.nextInt(); + // print fibonacci sequence less than N + int first = 0, second = 1; + //first fibo and second fibonacci are 0 and 1 respectively - int n = scn.nextInt(); - - int fn = 0, sn = 1; - - while(fn <= n){ - System.out.println(fn); + while(first <= N){ + //print first fibo 0 then add second fibo into it while updating second as well - int next = fn + sn; - fn = sn; - sn = next; + System.out.println(first); + + int next = first+ second; + first = second; + second = next; } }