everyone! I'm trying to solve this for school. I need to count how many steps it takes to come from any positive integer down to 1. And I'm supposed to use TypeScript. The Collatz Conjecture or 3x+1 problem can be summarized as follows: Take any positive integer n. If n is even, divide n by 2 to get n / 2. If n is odd, multiply n by 3 and add 1 to get 3n + 1. Repeat the process indefinitely. The conjecture states that no matter which number you start with, you will always reach 1 eventually. Here is my guess of code:
function steps(n: number) {
let counter: number = 0;
if (n > 0 && Number.isInteger(n)) {
while (n !== 1) {
if (n % 2 === 0) {
n = n / 2;
counter++;
} else if (n % 2 !== 0) {
n = (n * 3) + 1;
counter++;
}
return counter;
}
} else {
throw new Error('Only positive whole numbers are allowed');
}
}
I wanted my code as transparent as possible, that's why I might be writing too much code. Don't mind that.