Last active
December 31, 2015 21:59
-
-
Save taycaldwell/8050197 to your computer and use it in GitHub Desktop.
Collatz Conjecture for Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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