Home Introductory Problems | CSES
Post
Cancel

Introductory Problems | CSES

Weird Algorithm

Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until n is one.

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.Scanner;
public class Weird_Algorithm {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    long n = sc.nextLong();
    while (n > 1) {
      System.out.print(n + " ");
      n = n % 2 == 0 ? n / 2 : n * 3 + 1;
    }
    System.out.print(n);
  }
}
This post is licensed under CC BY 4.0 by the author.

Arrays & Strings | Codemonk | Hackerearth

Codechef Contests 2022