Lucas Numbers
Problem
Read n and print the first n Lucas numbers. The first two terms are 2 and 1. Every other term is the sum of the two terms before it: 2 1 3 4 7 11 18 ...
Constraints
- 0 <= n <= 60
Examples
Input
8
Output
2 1 3 4 7 11 18 29
Solutions
Each term is calculated from earlier terms and saved in an array.
/*
* Problem : Print the first n terms of the lucas numbers.
* Input : One integer n (number of terms).
* Output : The first n terms on one line, separated by a space.
* Approach: Calculate each term from the earlier terms.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int count = new Scanner(System.in).nextInt();
// Step 1: Make an array for the terms. Index 0 holds the first term.
long[] terms = new long[count];
// Step 2: Calculate the terms one by one.
for (int index = 0; index < count; index++) {
if (index < 2) {
// Step 3: The first 2 terms are given. Term 0 is 2 and term 1 is 1.
terms[index] = index == 0 ? 2 : 1;
} else {
// Step 4: Every other term comes from earlier terms. Add the two terms before it.
terms[index] = terms[index - 1] + terms[index - 2];
}
}
// Step 5: Print all terms on one line, separated by a space.
StringBuilder line = new StringBuilder();
for (int index = 0; index < count; index++) {
if (index > 0) {
line.append(" ");
}
line.append(terms[index]);
}
System.out.println(line);
}
}
Hints (2)
- Which terms are given at the start?
- Which earlier terms do you need for the next term?