Question:
A math class is implementing a method to calculate the nth term of a mathematical sequence. The sequence is defined as follows:
The first term is given by a, and each subsequent term is obtained by multiplying the previous term by a fixed ratio r.
Write a method named calculateNthTerm
that takes in three parameters:
a
: an integer representing the first term of the sequencer
: a double representing the fixed ratio between successive termsn
: an integer representing the nth term in the sequenceThe method should return the nth term of the sequence as a double.
You may assume that n
is a non-negative integer.
Your task is to implement calculateNthTerm
method.
Signature:
public static double calculateNthTerm(int a, double r, int n) {
// your code here
}
Example:
Input:
calculateNthTerm(2, 3.5, 4);
Output:
42
Explanation:
Given, the first term a = 2
, the fixed ratio r = 3.5
, and we need to find the 4th term n = 4
.
The sequence can be represented as (a, ar, ar^2, ar^3, ...).
So, the 4th term of the sequence is calculated as: a * r^(n-1) = 2 * (3.5)^(4-1) = 2 * (3.5)^3 = 42.