Click here to Skip to main content
15,885,871 members
Articles / Programming Languages / Java
Tip/Trick

Padovan sequence in core Java

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
12 Dec 2011CPOL 15.7K  
Padovan sequence in core Java
Padovan series are positive integers obtained by the following process: The Padovan series is the sequence of integers P(n) defined by the initial values P(0) = P(1) = P(2) = 1, and the recurrence relation P(n) = P(n - 2) + P(n - 3).
Write a program to generate the Padovan series from n to m.

Constraints:
  • n >=0 and m <=49.
  • m >= n.

If the given inputs are invalid or out of range, then return -1.

Example 1:
Input
from = 5
to = 10

Output:
returns {3, 4, 5, 7, 9, 12}

Explanation:

P(0) = P(1) = P(2) = 1, and the recurrence relation P(n) = P(n - 2) + P(n - 3). 
p(5) = p(5-2) + p(5-3) 
        = p(3) + p(2) -------- (1) 
p(3) = p(3-2) + p(3-1) 
        = p(1) + p(2) 
        = 1 + 1 
        = 2 
Substitute in (1) 
p(5) = 2 + 1 
        = 3 

Similarly the recurrence should continue for the remaining positions.

Example 2:
Input
from = 45
to = 60

Output
Returns {-1}

CODE TO IMPLEMENT THIS:

Java
import java.util.Scanner;
import java.util.ArrayList;

public class PadovanSeries
{
    public static void main(String[] arg)
    {
        Scanner read = new Scanner(System.in);
        System.out.println("Enter starting no. : ");
        int start = read.nextInt();
        System.out.println("Enter ending no. : ");
        int end = read.nextInt();
        int[] ans = getSeries(start, end);
        System.out.println("Padovan series : ");
        for (int a : ans)
            System.out.print(a + " ");
    }

    public static int[] getSeries(int s, int e)
    {
        ArrayList<Integer> list = new ArrayList<Integer>();
        int i, j = 0;
        for (i = s; i <= e; i++, j++)
            list.add(getPadovan(i));
        int[] ans = new int[j];
        for (i = 0; i < j; i++)
            ans[i] = list.get(i);
        return ans;
    }

    public static int getPadovan(int p)
    {
        if (p == 0 || p == 1 || p == 2)
            return 1;
        return (getPadovan(p - 2) + getPadovan(p - 3));
    }
}


http://en.wikipedia.org/wiki/Padovan_sequence [Check this link for get the information on Padovan Series.]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --