Tuesday 23 January 2018

 Printing a Series:

 Consider a series of number generated from the following formula

fn+1=fn-1+(fn-2)^2;

and the first two numbers are a0 = 0 and a1 = 1

Find the nth number of the series?

The logic to solve:

1) Generate the series using the above formula until nth term is obtained
2) Print the nth number in the series

Tips: As n can be a larger number so you need to choose a data type capable of handling the larger number.

Solution (Java Code):

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Demo {

    static BigInteger generateSeries(BigInteger t1, BigInteger t2, BigInteger n) {
        int condition=n.compareTo(new BigInteger("0"));
                if(condition==0)
                    return t2;
                else
                {
                        BigInteger one= new BigInteger("1");
                       
                        return generateSeries(t2,(t1.add(t2.multiply(t2))),n.subtract(one));
                   
                }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
       String a = in.next();
        String b = in.next();
        String c = in.next();
        BigInteger t1= new BigInteger(a);
                BigInteger t2= new BigInteger(b);
                BigInteger n= new BigInteger(c);

        BigInteger term= generateSeries(t1, t2, n.subtract(new BigInteger("2")));
        System.out.println(term);
        in.close();
    }

}