collatzPeak function

int collatzPeak(
  1. int n
)

Computes the maximum value reached in the Collatz sequence for a given positive integer.

Parameters:

  • n: A positive integer to start the sequence.

Returns:

  • The maximum value reached in the Collatz sequence starting from n.

Throws:

  • ArgumentError if n is not a positive integer.

Example:

print(collatzPeak(6));  // Output: 16
print(collatzPeak(27)); // Output: 9232

Implementation

int collatzPeak(int n) {
  if (n <= 0) {
    throw ArgumentError('Input must be a positive integer');
  }

  int maxValue = n;

  while (n != 1) {
    if (n.isEven) {
      n ~/= 2;
    } else {
      n = 3 * n + 1;
    }

    if (n > maxValue) {
      maxValue = n;
    }
  }

  return maxValue;
}