Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The juggler sequence is described as follows. Beginning with an input a1, the next term is defined by the recurrence relation

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

Task

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.

share|improve this question
2  
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 at 9:15
    
Reminds me of the Collatz conjecture (still unsolved) – wim Feb 16 at 4:13
    
@wim yes, it's very similar to that. – Seadrus Feb 16 at 15:55

20 Answers 20

up vote 6 down vote accepted

Jelly, 12 11 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.
share|improve this answer

Julia, 64 50 48 42 32 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!

share|improve this answer
    
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 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 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>

share|improve this answer
    
I sure wish ** were supported in all browsers. – ETHproductions Feb 16 at 15:18

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.

share|improve this answer

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!

share|improve this answer
    
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 at 13:50
    
Oh cool, thanks for letting me know! – David Feb 15 at 21:27

Mathematica, 40 39 bytes

Thanks to Martin Büttner for saving 1 byte.

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

Test case

%[5]
(* {5,11,36,6,2,1} *)
share|improve this answer

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.
share|improve this answer

APL, 28 24 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!

share|improve this answer

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.

share|improve this answer

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
share|improve this answer

Haskell, 70 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=[1]
g n=n:g(f n) 
share|improve this answer

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
share|improve this answer

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.

share|improve this answer
    
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 at 8:33

CJam, 18 bytes

ri{__2%.5+#i_(}g]p

Test it here

Similar to David's MATL answer.

share|improve this 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)))
share|improve this answer
    
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 at 8:46
    
Thanks @xnor, I have edited that in – Cameron Aavik Feb 15 at 9:07
    
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 at 0:33
    
I can also remove another byte off that by doing n<2or rather than n-1and – Cameron Aavik Feb 16 at 0:43

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.

share|improve this answer

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;}
share|improve this answer

TI-Basic, 30 Bytes

Prompt A
Repeat A=1
Disp A
int(A^(remainder(A,2)+.5->A
End
1
share|improve this answer
    
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 at 23:54

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.

share|improve this answer
    
You can golf this more. – lirtosiast Feb 15 at 4:52
    
@ThomasKwa Yeah, you're probably right. I'll think about it for a bit. – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 15 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;
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.