Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

5 of 5
added 38 characters in body
cole
  • 4k
  • 1
  • 14
  • 26

J, (削除) 49 (削除ここまで) 45 bytes

-4 bytes thanks to shorter Collatz Sequence code taken from @randomra's comment here.

(2-~[:#(>&1*-:+2&|*+:+>:@-:)^:a:)^:(<101)i.1:

Outputs 101 for invalid results.

Try it online!

Explanation

Unsurprisingly, this explanation has become quickly outdated. I'm going to leave it in terms of the old 49 byte answer I had, which I'm including below. If you want an update, just let me know. The way that it finds the length of the recursive sequence remains the same, I've just used a shorter Collatz Sequence method.

(1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:)^:(<101)i.1:

Finding the length of the Collatz Sequence

This section of the code is the following

(1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:)

Here's the explanation:

(1 -~ [: # %&2`(1+3&*)@.(2&|) ^: (1&<) ^: a:) Given an input n
 ^: a: Apply until convergence, collecting
 each result in an array.
 ^: (1&<) If n > 1 do the following, else
 return n.
 (2&|) Take n mod 2.
 %&2 If n mod 2 == 0, divide by 2.
 (1+3&*) If n mod 2 == 1, multiply by 3 
 and add 1.
 # Get the length of the resulting
 array.
 1 -~ Subtract 1.

Unfortunately, the apply verb (^:) when told to store results stores the initial value too, so it means we're (like always) off by one. Hence why we subtract 1.

Finding the length of the recursive sequence

(1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:) ^: (< 101) i. 1: Given an input n.
 ^: (< 101) Apply 100 times,
 collecting results
 in an array.
(1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:) Collatz sequence length.
 i. 1: Index of first 1 (returns
 101, the length of the
 array if 1 not found).
cole
  • 4k
  • 1
  • 14
  • 26

AltStyle によって変換されたページ (->オリジナル) /