[Programmers / JAVA] Level 1 Collatz Conjecture (12943)
[Programmers / JAVA] Level 1 Collatz Conjecture (12943)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
This conjecture, proposed by a person named Collatz in 1937, states that if you repeat the following operation on a given number until it becomes 1, every number can be reduced to 1. The operation is as follows.
- If the input number is even, divide it by 2.
- If the input number is odd, multiply it by 3 and add 1.
- Repeat the same operation on the resulting number until it becomes 1.
For example, if the input number is 6, then 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1, reaching 1 in a total of 8 steps. Complete the function solution that returns how many times the above operation must be repeated. However, if it does not become 1 even after 500 repetitions, return –1.
- The input number, num, is an integer that is at least 1 and less than 8000000.
| n | result |
|---|---|
| 6 | 8 |
| 16 | 4 |
| 626331 | -1 |
Example #1
Same as described in the problem.
Example #2
16 -> 8 -> 4 -> 2 -> 1, reaching 1 in a total of 4 steps.
Example #3
626331 does not become 1 even after 500 attempts, so it should return -1.
Let's turn every number into 1 through the operation called the Collatz conjecture. However, if 500 or more operations are performed, we simply return -1.
- If the input number is even, divide it by 2.
- If the input number is odd, multiply it by 3 and add 1.
- Repeat the same operation on the resulting number until it becomes 1.
The procedure for the Collatz conjecture is very simple, as shown above.
Let's implement the algorithm that repeats the above operation.
When case 3 returns 488 instead of -1
Unlike case 3 which is supposed to be -1, if you actually run it, there are cases where the operation is performed correctly but 488 comes out.
This happens because of an incorrect signature in the initial function. The initial function is public int solution(int num), but num needs to be declared as long instead of int to avoid errors.
If num is int, during the operation it exceeds the maximum value of int (about 2.1 billion), causing the number to overflow and corrupt the calculation. So simply changing it to public int solution(long num) will make it work correctly.
JAVA
/** * Collatz Conjecture class * * @author RWB * @since 2021.12.13 Mon 21:34:17 */ class Solution { /** * Method that returns the answer * * @param num: [long] integer * * @return [int] answer */ public int solution(long num) { int count = 0; while (num != 1) { // If performed 500 times if (count == 500) { count = -1; break; } num = num % 2 == 0 ? num / 2 : num * 3 + 1; count++; } return count; } }
