0

How can I print the Fibonacci series using only 2 variables?

java

9th Feb 2017, 3:45 PM
Rishi Bhattacharya
Rishi Bhattacharya - avatar
3 Answers
+ 3
normaly i dont like it to just write the code :D but here it is: public class Program { public static long fib(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return fib(n-1) + fib(n-2); } } public static void main(String[] args){ for(int i=0; i < 25; i++) { System.out.println(i + ": " + fib(i)); } } }
9th Feb 2017, 4:11 PM
R4xx4r
R4xx4r - avatar
+ 1
public class Program { public static void main(String[] args) { int number = 0; int add = 0; while (true) { if (add == 0) { System.out.println(number); add++; } else { System.out.println(add); System.out.println(number); } add += number; number += add; } } }
9th Feb 2017, 4:08 PM
Sam
+ 1
https://jsfiddle.net/jayanthns/gx8kg3us/ // javascript // var n = prompt("enter value of length"); var a = 0, b = 1; if(n > 1) { document.write(a+"<br>"); n--; } if(n > 1) { document.write(b+"<br>"); n--; } while(n>0) { document.write((a+b)+"<br>"); b = a+b; a = b - a; n--; } // Java// int n = 10; int a = 0, b = 1; System.out.println(a); System.out.println(b); n = n-2; while(n > 0) { System.out.println(a+b); b = a + b; a = b - a; n--; }
27th Jul 2017, 4:52 PM
Jayanth ns
Jayanth ns - avatar