RE: [Golfing] Collatz Conjecture 08-22-2015, 12:29 PM
#31
(08-22-2015, 09:55 AM)OversouL Wrote: Oh, I divided the odd number by 3. XD
Code:#include <iostream> int main(){int n;std::cin >> n;while(n > 1){n%2==0?n/=2:n=n*3+1;std::cout<<n<<" ";}return 0;}
I wonder why n*=3+1 doesn't work, like n=n*3+1 ??? Anyway, it's 114 bytes now.
Code:#include <iostream> int main(){int n;std::cin>>n;while(n>1){n%2==0?n/=2:n=n*3+1;std::cout<<n<<" ";}return 0;}
110 bytes after removing some spaces. :3
The reason you can't do n*=3+1 is because the *= assignment operator multiplies the left by everything on the right. Essentially, it's doing n=n*(3+1).
Speaking of shortening, you can change the ternary expression to be part of an assignment. So you can do n=n%2==0?n/2:3*n+1;
Furthermore, you can change the condition for the ternary to be just n%2. This is essentially the same logic I used. The reason for this is that n%2 will always return 0 or 1, where 0 is a "falsy" value and 1 is a "truthy" value. So, you can rearrange the statement to become n=n%2?3*n+1:n/2;

That's a good start, I think. You should also try to use command-line arguments so you don't need that long code to get it from STDIN.
![[Image: CDUAq9d.png]](http://i.imgur.com/CDUAq9d.png)





![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)


















![[Image: dHJ4Beo.gif]](http://i.imgur.com/dHJ4Beo.gif)