Skip to content

Collatz Conjecture

Problem Description

Given two integers A and B, where A is the first element of the sequence then find Bth element of the sequence.

If the kth element of the sequence is X then k+1th element calculated as:

  • if X is even then next element is X/2.
  • else next element is 3×X + 1.

Problem Constraints

1 <= A <= 10^9
1 <= B <= 10^5

Input Format

Given two integers A and B.

Output Format

Return an integer.

Example Input

Input 1:
A = 1
B = 3

Input 2:
A = 5
B = 6

Example Output

Output 1:
2

Output 2:
1

Example Explanation

Explanation 1:
 The sequence is as follows 1 -> 4 -> 2

Explanation 2:
The sequence is as follows 5 -> 16 -> 8 -> 4 -> 2 -> 1

Solution

swift
import Foundation

class Solution {
	func solve(_ A: inout Int, _ B: inout Int) -> Int64 {
        var ret:Int64 = Int64(A)
        var last:Int64 = Int64(A)
        for i in 2...B {
            ret = (last%2==0) ? last/2 : 3*last+1
            last = ret
        }
        return ret
	}
}

References