Continue a Geometric Sequence
Problem statement
You are given a prefix sequence and a nonnegative integer count. Return the next count terms in order.
For this exercise, assume the prefix belongs to a geometric sequence with one constant integer ratio r: each term after the first equals the previous term multiplied by r. The first term is nonzero and at least two terms are supplied, so r = sequence[1] / sequence[0] is uniquely defined.
For this exercise, assume this geometric rule is the intended continuation of the reported prefix [-2,6,-18,54,-162], whose ratio is -3. A finite prefix alone could also fit other rules; those alternatives are outside this practice contract.
For this exercise, assume the supplied prefix is valid and every supplied or requested term fits the stated integer bounds. Do not return the prefix itself. If count = 0, return an empty array.
Complete nextGeometricTerms(sequence, count) and return an array of signed64-bit integers.
Function
nextGeometricTerms(sequence: long[], count: int) → long[]Examples
Example 1
sequence = [-2,6,-18,54,-162]count = 3return = [486,-1458,4374]The ratio is 6 / -2 = -3. Starting from -162, multiply by -3 three times to obtain 486, -1458 and 4374.
Example 2
sequence = [5,0,0]count = 3return = [0,0,0]The first two terms determine ratio 0. Every later term is zero; division by the final zero term is unnecessary.
Example 3
sequence = [7,-7,7]count = 2return = [-7,7]The ratio is -1, so the sign alternates while the magnitude stays seven.
Example 4
sequence = [3,6]count = 0return = []No new terms are requested.
Constraints
- For this exercise, assume
2 <= sequence.length <= 20and0 <= count <= 20. - The first term is nonzero. The constant integer ratio satisfies
-10 <= r <= 10. - For this exercise, assume every supplied and requested term lies in
[-10^18,10^18]. - The supplied terms exactly satisfy the geometric rule; validity checking is not part of the task.