Sobes.tech
Middle+

Write a function to calculate the n-th term of a numerical sequence, where the n-th term equals the sum of the two previous ones, the first term is 3, the second is 2 (sequence: 3, 2, 5, 7, 12, ...).

sobes.tech AI

Answer from AI

Function to compute the n-th term of a sequence where each term is the sum of the two previous ones, starting with initial values 3 and 2:

function sequence(n) {
  if (n === 1) return 3;
  if (n === 2) return 2;
  let a = 3, b = 2, c;
  for (let i = 3; i <= n; i++) {
    c = a + b;
    a = b;
    b = c;
  }
  return c;
}

// Example usage:
console.log(sequence(5)); // Outputs 12

This function uses an iterative approach for efficient computation without recursion.