Wednesday, 5 July 2017

Java Code to generate the Lucas Sequence

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]

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

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...