Problem:
Design an algorithm to find the Fibonacci Series
0 1 1 2 3 5 8 13 .....
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
int n = s.nextInt();
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(0);
numbers.add(1);
for(int i = 2; i<n; i++){
numbers.add(i, numbers.get(i-2) + numbers.get(i-1));
}
System.out.println(numbers);
s.close();
}
}
Output:
enter the n value
10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Design an algorithm to find the Fibonacci Series
0 1 1 2 3 5 8 13 .....
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
int n = s.nextInt();
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(0);
numbers.add(1);
for(int i = 2; i<n; i++){
numbers.add(i, numbers.get(i-2) + numbers.get(i-1));
}
System.out.println(numbers);
s.close();
}
}
Output:
enter the n value
10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
enter the n value
15
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
No comments:
Post a Comment