Skip to content

Instantly share code, notes, and snippets.

@taycaldwell
Last active December 31, 2015 21:59
Show Gist options
  • Save taycaldwell/8050197 to your computer and use it in GitHub Desktop.
Save taycaldwell/8050197 to your computer and use it in GitHub Desktop.
Collatz Conjecture for Java
/*
* Rithms
* collatz.java
*
* Collatz Conjecture - Start with a number n > 1.
* Find the number of steps it takes to reach one
* using the following process: If n is even, divide
* it by 2. If n is odd, multiply it by 3 and add 1.
*/
import java.util.Scanner;
public class collatz {
/**
* @param args
*/
public static void main(String[] args) {
int steps = 0;
System.out.println("Enter a number:");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int x = n;
while(n > 1){
if(n % 2 == 0)
n /= 2;
else n = (n * 3) + 1;
steps++;
}
System.out.println("It takes \'" + steps + "\' steps to reach \'1\' using the Collatz conjecture on the number \'" + x +"\'.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment