TopcoderArchiveVisit Topcoder
SRM25 Jan 2003
SRM 130

Collatz

Problem statement, definition, constraints, and public examples.

Problem Statement

The Collatz Problem asks whether the following function will reach 1 for all positive k if we keep applying it:
      { if k is odd    :   3*k +1 
f(k)= {
      { if k is even   :    k/2
For example, lets say you were given k = 20:
f(20) = 10     First application
f(10) = 5      Second application
f(5)  = 16     Third application
f(16) = 8      Fourth application
f(8)  = 4      Fifth application
f(4)  = 2      Sixth application
f(2)  = 1      Seventh application

So for k = 20 this function required 7 applications of the function to reach 1. Given an int k return the number of applications required to reach 1. Topcoder has ensured that the number of applications will be less than 1000 and that any temporary value will not overflow a 32-bit integer.

Definition

Class:
Collatz
Method:
numSteps
Parameters:
int
Returns:
int
Method signature:
int numSteps(int k)
(be sure your method is public)

Constraints

  • k will be between 2 and 100000 inclusive.
  • The return value will be less than 1000.

Examples

  1. 20
    Returns: 7
    The example from above
  2. 2
    Returns: 1
    Just a single application required
  3. 5
    Returns: 5
    5*3+1 = 16 16/2 = 8 8/2 = 4 4/2 = 2 2/2 = 1
  4. 99999
    Returns: 226
  5. 77671
    Returns: 231
Back to all problems