# Output the Juggler sequence

The Juggler sequence is described as follows. Beginning with an input $$\a_1\$$, the next term is defined by the recurrence relation

$$a_{k+1} = \begin{cases} \left\lfloor a_k ^ \frac 1 2 \right\rfloor,\text{ if } a_k \text{ is even} \\ \left\lfloor a_k ^ \frac 3 2 \right\rfloor,\text{ if } a_k \text{ is odd} \\ \end{cases}$$

The sequence terminates when it reaches 1, as all subsequent terms would then be 1.

Given an input $$\n\$$ greater than or equal to 2, write a program/function/generator/etc. that outputs/returns the respective juggler sequence. The output can be in any reasonable form. You may not use a built-in that computes the juggler sequence, or any built-in that directly yields the result. You may assume that the sequence terminates in $$\1\$$.

## Test Cases

Input: output
2: 2, 1
3: 3, 5, 11, 36, 6, 2, 1
4: 4, 2, 1
5: 5, 11, 36, 6, 2, 1


This is a code golf. Shortest code in bytes wins.

• I got a little nerd sniped and computed the number of steps to halt for the first ~5.6*10^7 values (they all halt so far). – Michael Klein Feb 15 '16 at 9:15
• Reminds me of the Collatz conjecture (still unsolved) – wim Feb 16 '16 at 4:13
• @wim yes, it's very similar to that. – Seadrus Feb 16 '16 at 15:55

# Jelly, 1211 10 bytes

*BṪ×½Ḟµ’Ð¿


Thanks to @Sp3000 for golfing off 1 byte!

Try it online!

### How it works

*BṪ×½Ḟµ’Ð¿    Main link. Input: n

*B            Elevate n to all of its digits in base 2.
Ṫ           Extract the last power.
This yields n ** (n % 2).
×½         Multiply with sqrt(n). This yields n ** (n % 2 + 0.5).
Ḟ        Floor.

µ       Push the previous chain on the stack and begin a new, monadic chain.
Ð¿    Repeat the previous chain while...
’        n - 1 is non-zero.
Collect all intermediate results in an array.

• I'm almost afraid asking, since the poster has 87k reputation, but is it really possible to represent this in 10 bytes? You're using 10 characters, but can you really fit all of these very esoteric characters into only 256 combinations? ½, Ḟ, Ð would not seem to be my first choices for characters to add into my alphabet, considering I only have 256 places to fill... – Annonymus Jul 17 '16 at 16:54
• @Annonymus Jelly uses a custom code page that encodes each of the 256 characters it understands as a sinlge byte each. – Dennis Jul 17 '16 at 17:20
• I see! Thanks. Btw, I found a bug in your table, character 20 (I'm assuming it's a space, if it isn't the "bug" is that this is unclear) gets removed since it is a lonely space, you should use &nbsp; instead. – Annonymus Jul 17 '16 at 17:29
• @Annonymus Yes, that looked a little weird. I didn't want to use NBSP since any attempt to copy the table would break, but <code> </code> instead of the backticks seems to display an actual SP character. Thanks for pointing that out. – Dennis Jul 17 '16 at 18:24

# Julia, 6450484232 30 bytes

g(x)=[x;x<3||g(x^(x%2+.5)÷1)]


This is a recursive function that accepts an integer and returns a float array.

We build an array by concatenating the input with the next term of the sequence, computed as x to the power of its parity plus 1/2. This gives us either x1/2 or x1+1/2 = x3/2. Integer division by 1 gets the floor. When the condition x < 3 is true, the final element will be a Boolean rather than a numeric value, but since the array is not of type Any, this is cast to have the same type as the rest of the array.

Saved 14 bytes thanks to Dennis!

• Can the Julia interpreter handle source code in ISO 8859-1? Then the integer division would only be a single byte. – Martin Ender Feb 15 '16 at 9:57
• @MartinBüttner No, I've tried it before and it got pretty mad. Julia's parser assumes UTF-8. – Alex A. Feb 15 '16 at 17:03

# JavaScript (ES7), 45 33 bytes

f=n=>n<2?n:n+","+f(n**(.5+n%2)|0)


## Explanation

Recursive approach. Returns a comma-separated string of numbers.

f=n=>
n<2?n:          // stop when n == 1
n               // return n at the start of the list
+","+f(         // add the rest of the sequence to the list
n**(.5+n%2)|0 // juggler algorithm
)


## Test

** not used in test for browser compatibility.

f=n=>n<2?n:n+","+f(Math.pow(n,.5+n%2)|0)
<input type="number" oninput="result.textContent=f(+this.value)" />
<pre id="result"></pre>

• I sure wish ** were supported in all browsers. – ETHproductions Feb 16 '16 at 15:18
• @ETHproductions I sure wish ** were supported in C#. – aloisdg Jul 17 '16 at 17:34

# Mathematica, 40 39 bytes

Thanks to Martin Büttner for saving 1 byte.

NestWhileList[⌊#^.5#^#~Mod~2⌋&,#,#>1&]&


Test case

%
(* {5,11,36,6,2,1} *)


# Pyth, 14 12 bytes

.us@*B@N2NNQ


Demonstration

We start with a cumulative reduce, .u, which in this case starts at the input and applies a function until the result repeats, at which point it outputs all of the intermediate results.

The function takes the previous value as N. It starts by taking its square root with @N2. Next, it bifurcates that value on multiplication by N with *B ... N. This creates the list [N ** .5, (N ** .5) * N], the unfloored results for the even and odd cases. Next, the appropriate unfloored result is selected by indexing into the list with @ ... N. Since Pyth has modular indexing, no out-of-bounds errors are thrown. Finally, the result is floored with s.

# MATL, 13 12 bytes

tt2\.5+^ktq


Try it online!

Explanation

     % do...while loop
tt   % duplicate top of stack twice, takes implicit input on first iteration
2\    % take a_k mod 2
.5+^  % adds 0.5, to give 1.5 if odd, 0.5 if even, and takes a_k^(0.5 or 1.5)
kt    % Rounds down, and duplicates
q     % Decrement by 1 and use for termination condition---if it is 0, loop will finish


Thanks Luis for saving a byte!

• The floor function has been changed to k, so you can use that instead of Zo to save 1 byte. (Sorry for these changes; you can see the release summaries here) – Luis Mendo Feb 15 '16 at 13:50
• Oh cool, thanks for letting me know! – David Feb 15 '16 at 21:27

## Minkolang 0.15, 25 bytes

ndN(d$7;r2%2*1+;YdNd1=,).  Try it here! ### Explanation n Take number from input => n dN Duplicate and output as number ( Open while loop d Duplicate top of stack => n, n$7                      Push 0.5
;                     Pop b,a and push a**b => n, sqrt(n)
r                    Reverse stack => sqrt(n), n
2%                  Modulo by 2
2*                Multiply by 2
1+              Add 1 => sqrt(n), [1 if even, 3 if odd]
;             Pop b,a and push a**b => sqrt(n)**{1,3}
Y            Floor top of stack
dN          Duplicate and output as number
d1=,      Duplicate and => 0 if 1, 1 otherwise
).    Pop top of stack and end while loop if 0, then stop.


## TSQL, 89 bytes

Input goes in @N:

DECLARE @N INT = 5;


Code:

WITH N AS(SELECT @N N UNION ALL SELECT POWER(N,N%2+.5) N FROM N WHERE N>1)SELECT * FROM N


# APL, 2824 16 bytes

{⌊⍵*.5+2|⎕←⍵}⍣=⎕


This is a program that accepts an integer and prints the successive outputs on separate lines.

Explanation:

{           }⍣=⎕   ⍝ Apply the function until the result is the input
⌊⍵*.5+2|⎕←⍵       ⍝ Print the input, compute floor(input^(input % 2 + 0.5))


Try it online

Saved 8 bytes thanks to Dennis!

## Java 7, 83 71 bytes

void g(int a){System.out.println(a);if(a>1)g((int)Math.pow(a,a%2+.5));}


I originally used a typical for loop, but I had to jump through hoops to get it working right. After stealing borrowing user81655's idea to recurse instead, I got it down twelve bytes.

Haskell doesn't have integer sqrt built-in, but I think there may be something shorter than floor.sqrt.fromInteger.

s=floor.sqrt.fromInteger
f n|odd n=s$n^3|1<2=s n g 1= g n=n:g(f n)  # Oracle SQL 11.2, 128 bytes WITH v(i)AS(SELECT :1 FROM DUAL UNION ALL SELECT FLOOR(DECODE(MOD(i,2),0,SQRT(i),POWER(i,1.5)))FROM v WHERE i>1)SELECT i FROM v;  Un-golfed WITH v(i) AS ( SELECT :1 FROM DUAL UNION ALL -- SELECT FLOOR(POWER(i,0.5+MOD(i,2))) FROM v WHERE i>1 SELECT FLOOR(DECODE(MOD(i,2),0,SQRT(i),POWER(i,1.5))) FROM v WHERE i>1 ) SELECT * FROM v;  Adding MOD(i,2) to .5 is shorter but there is a bug with POWER(2,.5) : SELECT POWER(4,.5), FLOOR(POWER(4,.5)), TO_CHAR(POWER(4,.5)) FROM DUAL  gives 2 1 1,99999999999999999999999999999999999999  # R, 54 51 bytes z=n=scan();while(n>1){n=n^(.5+n%%2)%/%1;z=c(z,n)};z  Saved 3 bytes thanks to plannapus. • Given that all n are positive, one can shorten floor(n^(.5+n%%2)) to n^(.5+n%%2)%/%1 I think. +1 Nonetheless. – plannapus Feb 15 '16 at 8:33 # CJam, 18 bytes ri{__2%.5+#i_(}g]p  Test it here Similar to David's MATL answer. # Python 3, 57, 45, 43, 41 bytes Better Solution with suggestion from @mathmandan def a(n):print(n);n<2or a(n**(.5+n%2)//1)  This method will print each number on a new line Previous Solution: Cut down to 43 bytes after xnor's recommendation a=lambda n:[n][:n<2]or[n]+a(n**(n%2+.5)//1)  You can call the above by doing a(10) which returns [10, 3.0, 5.0, 11.0, 36.0, 6.0, 2.0, 1.0] The above will output the values as floats. If you want them as integers, then we can just add an extra 2 bytes for 43 bytes: def a(n):print(n);n<2or a(int(n**(.5+n%2)))  • It's a bit shorter to handle the base case by doing [n][:n<2]or, or as 1/n*[n]or for the integer case. – xnor Feb 15 '16 at 8:46 • Using Python 2, you can get it down to 41 bytes with def j(n):print n;n-1and j(n**(.5+n%2)//1). (Or in Python 3, def j(n):print(n);n-1and j(n**(.5+n%2)//1) is 42 bytes.) It'll print the sequence term by term instead of collecting the terms in a list. – mathmandan Feb 16 '16 at 0:33 • I can also remove another byte off that by doing n<2or rather than n-1and – Cameron Aavik Feb 16 '16 at 0:43 ## TI-Basic, 30 Bytes Prompt A Repeat A=1 Disp A int(A^(remainder(A,2)+.5->A End 1  • 22 bytes if you take input from Ans, replace Repeat Ans=1 with While log(Ans, and use √(Ans)Ans^remainder(Ans,2. – lirtosiast Feb 18 '16 at 23:54 # JavaScript ES6, 109 102 bytes s=>(f=n=>n==1?n:n%2?Math.pow(n,3/2)|0:Math.sqrt(n)|0,a=[s],eval("while(f(s)-1)a.push(s=f(s))"),a+",1")  I know this can be golfed. Returns a string of comma-separated numbers. # C++, 122 bytes #include <iostream> void f(int n){int i;while(n^1){std::cout<<n<<',';for(i=n*n;i*i>(n%2?n*n*n:n);i--);n=i;}std::cout<<1;}  # Retina, 144 bytes Input and output are in unary. The 2nd-to-last line contains a space, and the two middle lines and the last line are empty. {(\b|)11+$
$&¶$&
m-1=^(?=^(11)*(1?)).*&,$2 (1+),1$
$1;, 1(?=1*;)$%_
1+;
$%_ ;|, m-1=^ 1: +(1+):(11\1) 1$2:
1+:$|:1+ -1=(1+\b)$#1



Try it online

### Explanation

{(\b|)11+$# Loop, Duplicate last line$&¶$& m-1=^(?=^(11)*(1?)).*$     # Append ,n%2 to that line (number modulo 2)
$&,$2
(1+),1$# Cube that number if odd$1;,
1(?=1*;)
$%_ 1+;$%_
;|,                         # (Last stage of cubing number)

m-1=^                      # Integer square root of that number,
1:                          #   borrowed and modified from another user's answer
+(1+):(11\1)
1 $2: 1+:$|:1+

-1=(1+\b)
$#1  Integer square root in Retina, by Digital Trauma # C, 6463 61 bytes t;q(n){for(;!t;n=pow(n,.5+n%2))printf("%d%c ",n,n^1?44:t++);}  • You can replace n%2?1.5:0.5 with n%2+0.5 or .5+n%2 (if C allows it). If n%2 is true, n%2 is 1, else 0. – aloisdg Jul 17 '16 at 17:22 # Husk, 14 12 bytes U¡o⌊?^1.5√%2  Try it online! ## Explanation U¡ȯ⌊?^1.5√%2 ¡ iterate over the input infinitely, creating a list ȯ with the following three functions: take the previous result %2 modulo 2 ?^1.5 if truthy, raise to 3/2th power √ else take square root ⌊ floor the result U cut the list at fixed point  # TI BASIC, 43 bytes I'm pulling a Thomas Kwa and answering this one on my mobile. Input N Repeat N=1 Disp N remainder(N,2->B If not(B:int(sqrt(N->N If B:int(N^1.5->N End 1  Replace sqrt with the actual symbol on your calculator. Displays a linefeed separated list of numbers, which is a reasonable format. • You can golf this more. – lirtosiast Feb 15 '16 at 4:52 • @ThomasKwa Yeah, you're probably right. I'll think about it for a bit. – Conor O'Brien Feb 15 '16 at 19:47 # JavaScript ES6, 76 bytes Is a generator named j. To use, set a = j(<your value>);. To see the next value in the sequence, enter a.next().value. function*j(N){for(yield N;N-1;)yield N=(N%2?Math.pow(N,3/2):Math.sqrt(N))|0}  Ungolfed: function* juggler(N){ yield N; while(N!=1){ N = Math.floor(N % 2 ? Math.pow(N,3/2) : Math.sqrt(N)); yield N; } }  # C#, 62 bytes string f(int n)=>n+(n<2?"":","+f((int)Math.Pow(n,.5+n%2)));  Inspired by @user81655 and @Alex A., I used recursion. # F# 77 bytes Doesn't terminate at 1, but keeps going. let j=Seq.unfold(fun x->Some(x,floor(match x%2. with 0.->x**0.5|1.->x**1.5)))  Usage: j 3.;; > val it : seq<float> = seq [3.0; 5.0; 11.0; 36.0; ...]  Version that actually terminates at 1, 100 bytes let j=Seq.unfold(fun x->if x=1. then None else Some(x,floor(match x%2. with 0.->x**0.5|1.->x**1.5)))  Ungolfed let juggle input = let next x = floor (match x % 2. with | 0. -> x ** 0.5 | 1. -> x ** 1.5 | _ -> failwith "this should never happen") // addressing a compiler warning Seq.unfold (fun x -> if x = 1. then None else Some(x, next x)) input  # Perl 5, 34 bytes 33, plus 1 for -pE instead of -e say;($_=int$_**($_%2+.5))-1&&redo


## Explanation

First, -p sets the variable $_ equal to the input from stdin. Then we start a block of code: 1. say prints $_.
2. $_=int$_**($_%2+.5) sets $_ equal to the integer part of {$_ to the power of {{$_ modulo 2} + 0.5}}, due to the magic of order of operations (operator precedence). This assignment returns the new value of $_, and 3. (...)-1&&redo tests that returned value, minus 1. If the difference is 0, do nothing; otherwise, redo this block. Finally, -p prints $_.

## Of equal length

Also uses -p.

say()-($_=int$_**($_%2+.5))&&redo  This: prints $_; assigns as above; tests whether the return value of say (which is 1), minus the new value of $_, is 0, and redoes the block if so; then prints $_ at the end.

# dc, 22 21 bytes

[pd2%2*1+^vd1<F]dsFxn


Explained:

[                # Begin macro definition
p               # Peek at top of stack (print without popping, followed by newline)
d               # Duplicate top of stack
2%              # Mod 2: If even, 0; if odd, 1
2*1+            # If even: 0*2+1==1; if odd: 1*2+1==3
^v              # Raise, then square root: equivalent to ^(0.5)' or ^(1.5)'
d1<F            # If result is not 1, run macro again
]dsFx            # Duplicate macro, store as F', execute
n                # Print the final "1"


There's a bug: When the input is 1, the output consists of two 1s.

# 05AB1E, 12 9 bytes

Δ=DÉ·>;mï


-3 bytes thanks to @ovs.

Outputs each result on a separate line.

Explanation:

Δ          # Loop until the result no longer changes:
=         #  Print the current value with trailing newline (without popping)
#  (which will be the implicit input-integer in the first iteration)
D        #  Duplicate the value
É       #  Pop the copy, and check if it's odd (1 if odd; 0 if even)
·      #  Double that
>     #  Increase it by 1
;    #  Halve it
m   #  Take the current value to the power this 1/2 or 3/2
ï  #  And then cast it to an integer to floor it

• By combining fixed-point and manual printing, this get a bit shorter: ΔD=É·>;mï. – ovs Oct 9 '20 at 11:42
• @ovs Ah nice. I hadn't thought about printing the results on separated newlines. That would have also resulted in a 10-byter in the infinite loop approach. But your 9-byter is even better by combining the fixed-point and printing indeed, thanks! :) – Kevin Cruijssen Oct 9 '20 at 11:49

# Jelly, 7 bytes

*Ḃ×½ḞµƬ


Try it online!

Basically Dennis' method, but updated to use the modern version of Jelly. I initially had 9 bytes, but switching to the ×½ method saved 2 bytes.

## How it works

*Ḃ×½ḞµƬ - Main link. Takes n on the left
`