Problem:
Generate the Lucas sequence which is a variation on the Fibonacci sequence are :
1 3 4 7 11 18 29 .......
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class LucasSequence {
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(1);
numbers.add(3);
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
7
[1, 3, 4, 7, 11, 18, 29]
Generate the Lucas sequence which is a variation on the Fibonacci sequence are :
1 3 4 7 11 18 29 .......
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class LucasSequence {
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(1);
numbers.add(3);
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
7
[1, 3, 4, 7, 11, 18, 29]
enter the n value
15
[1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364]
No comments:
Post a Comment