Tech

Weird Algorithm (CSES 1068)

Published
Published:
Table of Contents
CSES Problem Set — Chapters

Problem Link: Weird Algorithm

Approach

Simulate the Collatz sequence: if nn is even divide by 2, if odd multiply by 3 and add 1, until n=1n = 1.

Solution

#include <bits/stdc++.h>
using namespace std;
int main() {
    long long n; cin >> n;
    while (n != 1) {
        cout << n << " ";
        n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
    }
    cout << 1;
}
Support this post Sponsor