Editorial for Collatz Conjecture


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: hselenal

Python

N = int(input())

while True:
    print(N, end=" ")
    if N == 1:
        break
    if N % 2 == 0:
        N //= 2 
    else:
        N = 3 * N + 1

Java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long N = sc.nextLong();

        while (true) {
            System.out.print(N + " ");
            if (N == 1) break;
            if (N % 2 == 0)
                N /= 2;
            else
                N = 3 * N + 1;
        }
    }
}

C++

#include <iostream>
using namespace std;

int main() {
    long long N;
    cin >> N;

    while (true) {
        cout << N << " ";
        if (N == 1) break;

        if (N % 2 == 0)
            N /= 2; 
        else
            N = 3 * N + 1;
    }

    cout << endl;
    return 0;
}

Comments

There are no comments at the moment.