Fibonacci Modified

Back

Problem

We define a modified Fibonacci sequence using the following definition:

Given terms ti and ti+1 where i ∈ (1,∞), term ti+2 is computed using the following relation:
ti+2 = ti + (ti+1)2

For example, if t1 = 0 and t2 = 1,

  • t3 = 0 + 12 = 1,
  • t4 = 1 + 12 = 2,
  • t5 = 1 + 22 = 5,
  • and so on.

Given three integers, t1, t2, and n, compute and print the nth term of a modified Fibonacci sequence.

Function Description

Complete the fibonacciModified function in the editor below. It must return the nth number in the sequence.

fibonacciModified has the following parameter(s):

  • t1: an integer
  • t2: an integer
  • n: an integer

Note: The value of tn may far exceed the range of a 64-bit integer. Many submission languages have libraries that can handle such large results but, for those that don't (e.g., C++), you will need to compensate for the size of the result.

Input Format

A single line of three space-separated integers describing the respective values of t1, t2, and n.

Constraints

  • 0 ≤ t1,t2 ≤ 2
  • 3 ≤ n ≤ 20
  • tn may far exceed the range of a 64-bit integer.

Output Format

Print a single integer denoting the value of term tn in the modified Fibonacci sequence where the first two terms are t1 and t2.

Solution


// Complete the fibonacciModified function below.
static BigInteger fibonacciModified(int t1, int t2, int n) {
	
	BigInteger term = new BigInteger(0);
	BigInteger num1 = new BigInteger(t1);
	BigInteger num2 = new BigInteger(t2);
	
	for (int i = 0; i < n-2; i++)
	{
		term = num1 + (num2 * num2);
		num1 = num2;
		num2 = term;
	}
	
	return term;
}
			

Top