- Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCollatz.java
More file actions
Latest commit
36 lines (30 loc) · 885 Bytes
/
Copy pathCollatz.java
File metadata and controls
36 lines (30 loc) · 885 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
* Eden Ghirmai
* 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
*/
importjava.util.*;
publicclassCollatz {
publicstaticvoidmain(String[] args) {
Scannerconsole = newScanner(System.in);
System.out.println("Collatz Conjecture:");
System.out.print("Enter a number: ");
intnum = console.nextInt();
System.out.println("It takes " + solve(num) + " steps to reach 1 using the Collatz Conjecture,");
System.out.println("beginning with the number " + num + ".");
}
// collatz algorithm
// pre-condition: n > 1
publicstaticintsolve(intn) {
if (n == 1) {
return0;
} elseif (n % 2 == 0) {
return1 + solve(n / 2);
} else {
return1 + solve(n * 3 + 1);
}
}
}