Java program to generate Collatz Conjecture sequence.

import java.util.Scanner;

// © 2017 TheFlyingKeyboard
// theflyingkeyboard.net

public class CollatzConjecture {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int number;
    int iterNum = 0;
    
    System.out.print("Enter a number: ");
    number = input.nextInt();
    System.out.print(number + " ");
    
    if(number > 0){
      while(number != 1){
        number = collatzConjecture(number);
        System.out.print(number + " ");
        
        iterNum++;
      }
      
      System.out.println("");
      System.out.println("It took " + iterNum + " iterations to reach 1");
    }
  }
  
  static int collatzConjecture(int num)
    {
        if (num % 2 == 0)
        {
            return num / 2;
        }
        else
        {
            return 3 * num + 1;
        }
    }
}

 

Java Collatz Conjecture Sequence Generator
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *