Juggler sequence: Difference between revisions

Add C# implementation
(Corrected error in task description, see talk page.)
(Add C# implementation)
 
(4 intermediate revisions by 4 users not shown)
Line 49:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">F juggler(n)
V a = Int64(n)
V r_count = 0
Line 67:
L(n) 20..39
V (l, h, i) = juggler(n)
print(f:‘{n} {l:2} {h:14} {i}’)</langsyntaxhighlight>
 
{{out}}
Line 97:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F isqrt(BigInt x)
assert(x >= 0)
 
Line 133:
 
L(k) [113, 173, 193, 2183, 11229, 15065]
juggler(k)</langsyntaxhighlight>
 
{{out}}
Line 168:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
 
Line 245:
begin
Put_Table;
end Juggler;</langsyntaxhighlight>
{{out}}
<pre>
Line 275:
===Core language===
Keeping within AppleScript's usable number range:
<langsyntaxhighlight lang="applescript">on juggler(n)
script o
property sequence : {n}
Line 322:
end task
 
task()</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">"20: l[n] = 3, h[n] = 20, i[n] = 0
21: l[n] = 9, h[n] = 140, i[n] = 4
22: l[n] = 3, h[n] = 22, i[n] = 0
Line 344:
37: l[n] = 17, h[n] = 24906114455136, i[n] = 8
38: l[n] = 3, h[n] = 38, i[n] = 0
39: l[n] = 14, h[n] = 233046, i[n] = 3"</langsyntaxhighlight>
 
===Shell script===
One of AppleScript's main roles is telling other software to do things. This includes Unix executables, many of which come with the system. In the following, the 'do shell script' command feeds a script to the Bash shell, which script itself contains code to be passed to and executed by the "bc" executable. It's essentially a script within a script within a script. The text returned from "bc", which can handle larger numbers than core AppleScript, contains lines which are just the zeros returned by the 'juggler' function, so these are stripped out using "sed". The 'do shell script' command is supplied by the StandardAdditions OSAX which comes with the system as a standard AppleScript extension. So ironically, there's not a single command from the core language in the following code. But it's legitimate AppleScript and the input and output are both AppleScript text objects.
 
<langsyntaxhighlight lang="applescript">do shell script "echo '
define juggler(n) {
#auto temp,i,max,pos
Line 372:
juggler(30817); # Another 191 to here.
# juggler(48443) produced no result after running all night.
' | bc | sed -n '/^0$/ !p;'"</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">"20: l[n] = 3, h[n] = 20, i[n] = 0
21: l[n] = 9, h[n] = 140, i[n] = 4
22: l[n] = 3, h[n] = 22, i[n] = 0
Line 403:
15065: l[n] = 66, d[n] = 11723, i[n] = 25
15845: l[n] = 139, d[n] = 23889, i[n] = 43
30817: l[n] = 93, d[n] = 45391, i[n] = 39"</langsyntaxhighlight>
 
=={{header|BQN}}==
<langsyntaxhighlight lang="bqn">Juggle ← {
Step ← ⌊⊢⋆(0.5 + 2|⊢)
¯1‿0‿0 + 3↑{
Line 414:
}
 
>⟨"NLIH"⟩ ∾ (⊢∾Juggle)¨ 20+↕20</langsyntaxhighlight>
{{out}}
<Pre>┌─
Line 439:
39 14 3 233046
┘</pre>
 
 
=={{header|C#}}==
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
using System.Collections.Generic;
using System.Numerics;
 
public class JugglerSequence
{
public static void Main(string[] args)
{
Console.WriteLine(" n l[n] i[n] h[n]");
Console.WriteLine("---------------------------------");
for (int number = 20; number <= 39; number++)
{
JugglerData result = Juggler(number);
Console.WriteLine($"{number,2}{result.Count,7}{result.MaxCount,6}{result.MaxNumber,17}");
}
Console.WriteLine();
 
List<int> values = new List<int> { 113, 173, 193, 2183, 11229, 15065, 15845, 30817 };
Console.WriteLine(" n l[n] i[n] d[n]");
Console.WriteLine("----------------------------");
foreach (int value in values)
{
JugglerData result = Juggler(value);
Console.WriteLine($"{value,5}{result.Count,8}{result.MaxCount,7}{result.DigitCount,7}");
}
}
 
private static JugglerData Juggler(int number)
{
if (number < 1)
{
throw new ArgumentException("Starting value must be >= 1: " + number);
}
BigInteger bigNumber = new BigInteger(number);
int count = 0;
int maxCount = 0;
BigInteger maxNumber = bigNumber;
while (!bigNumber.Equals(BigInteger.One))
{
if (bigNumber.IsEven)
{
bigNumber = bigNumber.Sqrt();
}
else
{
BigInteger cubed = BigInteger.Pow(bigNumber, 3);
bigNumber = cubed.Sqrt(); // Approximating the cube root by taking the square root of the cubed value.
}
count++;
if (bigNumber.CompareTo(maxNumber) > 0)
{
maxNumber = bigNumber;
maxCount = count;
}
}
 
return new JugglerData(count, maxCount, maxNumber, maxNumber.ToString().Length);
}
 
private class JugglerData
{
public int Count { get; }
public int MaxCount { get; }
public BigInteger MaxNumber { get; }
public int DigitCount { get; }
 
public JugglerData(int count, int maxCount, BigInteger maxNumber, int digitCount)
{
Count = count;
MaxCount = maxCount;
MaxNumber = maxNumber;
DigitCount = digitCount;
}
}
}
 
public static class BigIntegerExtensions
{
public static BigInteger Sqrt(this BigInteger n)
{
if (n == 0) return 0;
if (n > 0)
{
int bitLength = Convert.ToInt32(Math.Ceiling(BigInteger.Log(n, 2)));
BigInteger root = BigInteger.One << (bitLength / 2);
 
while (!IsSqrt(n, root))
{
root += n / root;
root /= 2;
}
 
return root;
}
throw new ArithmeticException("NaN");
}
 
private static bool IsSqrt(BigInteger n, BigInteger root)
{
BigInteger lowerBound = root * root;
BigInteger upperBound = (root + 1) * (root + 1);
return n >= lowerBound && n < upperBound;
}
}
</syntaxhighlight>
{{out}}
<pre>
n l[n] i[n] h[n]
---------------------------------
20 3 0 20
21 9 4 140
22 3 0 22
23 9 1 110
24 3 0 24
25 11 3 52214
26 6 3 36
27 6 1 140
28 6 3 36
29 9 1 156
30 6 3 36
31 6 1 172
32 6 3 36
33 8 2 2598
34 6 3 36
35 8 2 2978
36 3 0 36
37 17 8 24906114455136
38 3 0 38
39 14 3 233046
 
n l[n] i[n] d[n]
----------------------------
113 16 9 27
173 32 17 82
193 73 47 271
2183 72 32 5929
11229 101 54 8201
15065 66 25 11723
15845 139 43 23889
30817 93 39 45391
 
</pre>
 
 
=={{header|C++}}==
{{trans|Go}}
{{libheader|GMP}}
<langsyntaxhighlight lang="cpp">#include <cassert>
#include <iomanip>
#include <iostream>
Line 490 ⟶ 639:
<< '\n';
}
}</langsyntaxhighlight>
 
{{out}}
Line 541 ⟶ 690:
=={{header|F_Sharp|F#}}==
This task uses [[Isqrt_(integer_square_root)_of_X#F.23]]
<langsyntaxhighlight lang="fsharp">
// Juggler sequence. Nigel Galloway: August 19th., 2021
let J n=Seq.unfold(fun(n,i,g,l)->if n=1I then None else let e=match n.IsEven with true->Isqrt n |_->Isqrt(n**3) in Some((i,g,l),if e>i then (e,e,l+1,l+1) else (e,i,g,l+1)))(n,n,0,0)|>Seq.last
printfn " n l[n] i[n] h[n]\n___________________"; [20I..39I]|>Seq.iter(fun n->let i,g,l=J n in printfn $"%d{int n}%5d{l+1}%5d{g} %A{i}")
printfn " n l[n] i[n] d[n]\n________________________"; [113I;173I;193I;2183I;11229I;15065I;15845I;30817I]|>Seq.iter(fun n->let i,g,l=J n in printfn $"%8d{int n}%5d{l+1}%5d{g} %d{(bigint.Log10>>int>>(+)1) i}")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 586 ⟶ 735:
=={{header|Factor}}==
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: combinators formatting generalizations io kernel math
math.extras math.functions.integer-logs math.order math.ranges
sequences strings tools.memory.private ;
Line 623 ⟶ 772:
 
{ 113 173 193 2183 11229 15065 15845 30817 }
[ integer-log10 1 + ] "d[n]" juggler.</langsyntaxhighlight>
{{out}}
<pre>
Line 670 ⟶ 819:
 
The next four record holders for the largest term (see talk page), are also doable but increased the overall time to nearly 24 minutes on my machine.
<langsyntaxhighlight lang="go">package main
 
import (
Line 730 ⟶ 879:
fmt.Printf("%11s %3d %3d %s\n", cn, count, maxCount, rcu.Commatize(digits))
}
}</langsyntaxhighlight>
 
{{out}}
Line 783 ⟶ 932:
Integer square root is computed as in [[Isqrt_(integer_square_root)_of_X#Haskell]]
 
<langsyntaxhighlight lang="haskell">import Text.Printf
import Data.List
 
Line 805 ⟶ 954:
mapM_ task [20..39]
putStrLn "\nTough guys\n"
mapM_ task [ 113, 173, 193, 2183, 11229, 15065, 15845, 30817 ]</langsyntaxhighlight>
 
<pre>n = 20 length = 3 maximal value at = 0 (20)
Line 841 ⟶ 990:
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">jug=: <.@^ 0.5+2|]</langsyntaxhighlight> would work if 64 bit floats were adequate for the task example, but they are not.
 
Instead, we take the square root of either the even number or the third power of the odd number:
 
<langsyntaxhighlight Jlang="j">jugx=: <.@%:@(^ 1x+2*2|])</langsyntaxhighlight>
 
Task examples:
<langsyntaxhighlight Jlang="j">require'format/printf'
 
task=: {{
Line 874 ⟶ 1,023:
37: l: 18, h: 24906114455136, i:8
38: l: 4, h: 38, i:0
39: l: 15, h: 233046, i:3</langsyntaxhighlight>
 
Sadly, J's extended precision implementation is antiquated (slow), hopefully that will be fixed before too long.
 
Still, some of the stretch exercises can be computed quickly:
<langsyntaxhighlight Jlang="j">taskx=: {{
echo '%d: l: %d, d: %d, i:%d' sprintf y;(#;#@":@(>./);]i.>./)jugx^:a: y
}}
Line 888 ⟶ 1,037:
193: l: 74, d: 271, i:47
2183: l: 73, d: 5929, i:32
11229: l: 102, d: 8201, i:54</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
 
import java.math.BigInteger;
import java.util.List;
 
public final class JugglerSequence {
 
public static void main(String[] aArgs) {
System.out.println(" n l[n] i[n] h[n]");
System.out.println("---------------------------------");
for ( int number = 20; number <= 39; number++ ) {
JugglerData result = juggler(number);
System.out.println(String.format("%2d%7d%6d%17d",
number, result.aCount, result.aMaxCount, result.aMaxNumber));
}
System.out.println();
List<Integer> values = List.of( 113, 173, 193, 2183, 11229, 15065, 15845, 30817 );
System.out.println(" n l[n] i[n] d[n]");
System.out.println("----------------------------");
for ( int value : values ) {
JugglerData result = juggler(value);
System.out.println(String.format("%5d%8d%7d%7d",
value, result.aCount, result.aMaxCount, result.aDigitCount));
}
}
private static JugglerData juggler(int aNumber) {
if ( aNumber < 1 ) {
throw new IllegalArgumentException("Starting value must be >= 1: " + aNumber);
}
BigInteger number = BigInteger.valueOf(aNumber);
int count = 0;
int maxCount = 0;
BigInteger maxNumber = number;
while ( ! number.equals(BigInteger.ONE) ) {
number = number.testBit(0) ? number.pow(3).sqrt() : number.sqrt();
count = count + 1;
if ( number.compareTo(maxNumber) > 0 ) {
maxNumber = number;
maxCount = count;
}
}
return new JugglerData(count, maxCount, maxNumber, String.valueOf(maxNumber).length());
}
private static record JugglerData(int aCount, int aMaxCount, BigInteger aMaxNumber, int aDigitCount) {}
 
}
</syntaxhighlight>
{{ out }}
<pre>
n l[n] i[n] h[n]
---------------------------------
20 3 0 20
21 9 4 140
22 3 0 22
23 9 1 110
24 3 0 24
25 11 3 52214
26 6 3 36
27 6 1 140
28 6 3 36
29 9 1 156
30 6 3 36
31 6 1 172
32 6 3 36
33 8 2 2598
34 6 3 36
35 8 2 2978
36 3 0 36
37 17 8 24906114455136
38 3 0 38
39 14 3 233046
 
n l[n] i[n] d[n]
----------------------------
113 16 9 27
173 32 17 82
193 73 47 271
2183 72 32 5929
11229 101 54 8201
15065 66 25 11723
15845 139 43 23889
30817 93 39 45391
</pre>
 
=={{header|jq}}==
Line 896 ⟶ 1,133:
The following jq program uses `idivide/1`, `isqrt/0`, and `lpad/1` as defined at
[[Isqrt_(integer_square_root)_of_X#jq]].
<langsyntaxhighlight lang="jq">def juggler:
. as $n
| if $n < 1 then "juggler starting value must be a positive integer." | error
Line 937 ⟶ 1,174:
| fmt(6; 6; 6; 8) );
 
task1, "", task2</langsyntaxhighlight>
{{out}}
<pre>
Line 976 ⟶ 1,213:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Formatting
 
function juggler(k, countdig=true, maxiters=20000)
Line 1,000 ⟶ 1,237:
2264915, 5812827])
@time juggler(7110201)
</langsyntaxhighlight>{{out}}
<pre>
n l(n) i(n) h(n) or d(n)
Line 1,043 ⟶ 1,280:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">next[n_Integer] := If[EvenQ@n, Floor[Sqrt[n]], Floor[n^(3/2)]]
 
stats[n_Integer] :=
Line 1,052 ⟶ 1,289:
{TableForm[Table[stats@n, {n, 20, 39}],
TableHeadings -> {None, {"n", "length", "max", "max pos"}}]</langsyntaxhighlight>
 
{{out}}<pre>
Line 1,080 ⟶ 1,317:
=={{header|Nim}}==
Using only standard library, so limited to values of <code>n</code> less than 40.
<langsyntaxhighlight Nimlang="nim">import math, strformat
 
func juggler(n: Positive): tuple[count: int; max: uint64; maxIdx: int] =
Line 1,098 ⟶ 1,335:
for n in 20..39:
let (l, h, i) = juggler(n)
echo &"{n} {l:2} {h:14} {i}"</langsyntaxhighlight>
 
{{out}}
Line 1,125 ⟶ 1,362:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Juggler_sequence
Line 1,156 ⟶ 1,393:
printf "%8d %4d %3d d(n) = %d digits\n", $i, $count, $at, length $max;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,200 ⟶ 1,437:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/juggler.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 1,251 ⟶ 1,488:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,301 ⟶ 1,538:
=={{header|Python}}==
Slowed to a crawl at n of 1267909, so did not run for larger n.
<langsyntaxhighlight lang="python">from math import isqrt
 
def juggler(k, countdig=True, maxiters=1000):
Line 1,322 ⟶ 1,559:
for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:
juggler(k)
</langsyntaxhighlight>{{out}}
<pre>
n l(n) i(n) h(n) or d(n)
Line 1,361 ⟶ 1,598:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ dip number$
over size -
space swap of
Line 1,395 ⟶ 1,632:
15 recho 2 recho cr ] is stats ( n --> )
 
20 times [ i^ 20 + stats ]</langsyntaxhighlight>
 
{{out}}
Line 1,423 ⟶ 1,660:
Reaches 30817 fairly quickly but later values suck up enough memory that it starts thrashing the disk cache and performance drops off a cliff (on my system). Killed it after 10 minutes and capped list at 30817. Could rewrite to not try to hold entire sequence in memory at once, but probably not worth it. If you want sheer numeric calculation performance, Raku is probably not where it's at.
 
<syntaxhighlight lang="raku" perl6line>use Lingua::EN::Numbers;
sub juggler (Int $n where * > 0) { $n, { $_ +& 1 ?? .³.&isqrt !! .&isqrt } … 1 }
 
Line 1,449 ⟶ 1,686:
printf "%10s %4d %4d %10s %6.2f seconds\n", .&comma, +@j-1, @j.first(* == $max, :k),
$max.chars.&comma, (now - $start);
}</langsyntaxhighlight>
{{out}}
<pre> n l[n] i[n] h[n]
Line 1,490 ⟶ 1,727:
 
Another optimization was to reduce the number of digits after the &nbsp; sqrt &nbsp; was calculated.
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays the juggler sequence for any positive integer*/
numeric digits 20 /*define the number of decimal digits. */
parse arg LO HI list /*obtain optional arguments from the CL*/
Line 1,546 ⟶ 1,783:
if z>mx then do; mx= z; imx= j; end /*found a new max; set MX; set IMX. */
#= z
end /*j*/; return j</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the inputs: &nbsp; &nbsp; <tt> , &nbsp; , &nbsp; 113 &nbsp; 173 &nbsp; 193 &nbsp; 2183 &nbsp; 11229 &nbsp; 15065 &nbsp; 30817 &nbsp; 48443 </tt>}}
<pre>
Line 1,584 ⟶ 1,821:
30,817 93 39 45,391
48,443 157 60 972,463
</pre>
 
=={{header|RPL}}==
≪ 0 SWAP DUP2
'''DO'''
DUP 2 MOD 1.5 0.5 IFTE ^ FLOOR
SWAP 1 + SWAP
'''IF''' 3 PICK OVER < '''THEN''' ROT DROP DUP ROT ROT 4 ROLL DROP OVER 4 ROLLD '''END'''
'''UNTIL''' DUP 1 == '''END'''
DROP SWAP R→B ROT 3 →LIST
≫ ''''JUGLR'''' STO
≪ { "n" "l[n}" "h[n}" "i[n}" }
20 39 '''FOR''' n { } n + n '''JUGLR''' + '''NEXT'''
≫ ''''TASK'''' STO
{{out}}
<pre>
21: { "n" "l[n}" "h[n}" "i[n}" }
20: { 20 3 #20 0 }
19: { 21 9 # 140d 4 }
18: { 22 3 # 22d 0 }
17: { 23 9 # 110d 1 }
16: { 24 3 # 24d 0 }
15: { 25 11 # 52214d 3 }
14: { 26 6 # 36d 3 }
13: { 27 6 # 140d 1 }
12: { 28 6 # 36d 3 }
11: { 29 9 # 156d 1 }
10: { 30 6 # 36d 3 }
9: { 31 6 # 172d 1 }
8: { 32 6 # 36d 3 }
7: { 33 8 # 2598d 2 }
6: { 34 6 # 36d 3 }
5: { 35 8 # 2978d 2 }
4: { 36 3 # 36d 0 }
3: { 37 17 # 24906114455136d 8 }
2: { 38 3 # 38d 0 }
1: { 39 14 # 233046d 3 }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def juggler(k) = k.even? ? Integer.sqrt(k) : Integer.sqrt(k*k*k)
 
(20..39).chain([113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915]).each do |k|
Line 1,603 ⟶ 1,878:
end
end
</syntaxhighlight>
</lang>
{{out}}
<pre>20: l[n] = 3, h[n] = 20, i[n] = 0
Line 1,645 ⟶ 1,920:
{{libheader|Wren-big}}
This took just over 17 minutes to reach n = 30,817 on my machine and I gave up after that.
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./big" for BigInt
 
var one = BigInt.one
Line 1,684 ⟶ 1,959:
var res = juggler.call(n)
Fmt.print("$,6d $3d $3d $,6i", n, res[0], res[1], res[3])
}</langsyntaxhighlight>
 
{{out}}
Line 1,727 ⟶ 2,002:
{{libheader|Wren-gmp}}
Massive speed-up, of course, when one brings in GMP. Now takes about 1 minute 48 seconds to reach 7,110,201 which is not much slower than Go on the same machine!
<langsyntaxhighlight ecmascriptlang="wren">/* juggler-gmpJuggler_sequence_2.wren */
 
import "./gmp" for Mpz
Line 1,772 ⟶ 2,047:
var res = juggler.call(n)
Fmt.print("$,9d $3d $3d $,i", n, res[0], res[1], res[3])
}</langsyntaxhighlight>
 
{{out}}
338

edits