Padovan Sequence
Problem
Read n and print the first n terms of the Padovan sequence. The first three terms are 1, 1 and 1. Every other term is the sum of the term two places back and the term three places back: 1 1 1 2 2 3 4 5 7 9 ...
Constraints
- 0 <= n <= 60
Examples
Input
10
Output
1 1 1 2 2 3 4 5 7 9
Solutions
Each term is calculated from earlier terms and saved in an array.
/*
* Problem : Print the first n terms of the padovan sequence.
* 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 < 3) {
// Step 3: The first 3 terms are given. The first three terms are all 1.
terms[index] = 1;
} else {
// Step 4: Every other term comes from earlier terms. Add the terms at index - 2 and index - 3. The term just before it is not used.
terms[index] = terms[index - 2] + terms[index - 3];
}
}
// 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 (1)
- Look at which earlier terms are used: not the previous one.