title: Convert maximum values to bit widths

text:
# Question
Title: Convert maximum values to bit widths
## Background

The newest version of the C standard, C23, adds preprocessor macros like `INT_WIDTH`, `ULONG_WIDTH`, and `SIZE_WIDTH` that tell you the bit width of various integer types (here, `int`, `unsigned long`, and `size_t`, respectively). However, while the majority of us are stuck with pre-C23 compilers/standard libraries, it would still be nice to have these values available to us.

What we do have easy access to is the numerical limits of the integer types, e.g. `INT_MAX`, `ULONG_MAX`, and `SIZE_MAX`. For unsigned types, these values are guaranteed to be of the form \\$2^n - 1\\$. If we could extract the \\$n\\$ from numbers like this, that would give us the width of every (unsigned) integer type.

## Objective

Your goal is to write a C preprocessor macro `MAX_TO_WIDTH(m)` which converts unsigned `_MAX` values to the corresponding `_WIDTH` value. More precisely, \\$\texttt{MAX\_TO\_WIDTH}(2^n - 1) = n\\$ for all \\$n\\$ in a "reasonable" range (see below). For example, we need `MAX_TO_WIDTH(255) == 8`, `MAX_TO_WIDTH(4294967295) == 32`, etc. Your macro will not be called with other values, so `MAX_TO_WIDTH(10)` can return a garbage value, or even invalid code.

Because macro substitution works by pasting token sequences without evaluating them, fairly succinct macros can have very large expansions. Therefore, instead of golfing the macro itself, we will be golfing its *output*.

## Rules

1. Your submission should be a C macro definition like

```
#define MAX_TO_WIDTH(m) ...

```

You may also define and use any helper macros you want to.
2. `MAX_TO_WIDTH(m)` must give the correct result for all \\$m = 2^n - 1\\$, \\$n \in \[1, 128\]\\$. Most C preprocessors that I know of only handle up to 64-bit integers, but new architectures like CHERI will have 128-bit pointers (and thus `MAX_TO_WIDTH(UINTPTR_MAX) == 128`. You should verify that your implementation works up to at least 128 bits, for example by translating it to Python.
3. For valid inputs, your macro should produce an integer constant expression suitable for use in a preprocessor condition. That means things like this must work:

```
#if MAx_TO_WIDTH(255) == 8
switch (8) {
    case MAX_TO_WIDTH(255):
        break;
    default:
        assert(0);
}
#endif

```

The C preprocessor has slightly different rules than C itself for evaluating expressions (particularly around overflow). The result should be correct in either context. The test cases attempt to validate this for you.
4. Your macro must properly parenthesize its input and output. If you're unfamiliar with C, this means that macros like

```
#define FOO(x) 2 * x + 1

```

Are bad practice because `2 * FOO(1 + 1)` expands to `2 * 2 * 1 + 1 + 1` (a.k.a. 6, not the desired 10). The macro should instead be written

```
#define FOO(x) (2 * (x) + 1)

```

The test cases attempt to validate this for you.

## Testing

Add the following code after your macro definition to test it:

```
/* Check validity in preprocessor conditions */
#if 2 * MAX_TO_WIDTH(1 + 1 + 1) != 4
#error "Expected MAX_TO_WIDTH(3) == 2"
#endif

/* Calculate (1 << n) - 1, without overflow */
#define WIDTH_TO_MAX(n) ((((1ULL << ((n) - 1)) - 1) << 1) + 1)

/* Check that MAX_TO_WIDTH() inverts WIDTH_TO_MAX() */
#define ASSERT_WIDTH(n) _Static_assert(MAX_TO_WIDTH(WIDTH_TO_MAX(n)) == (n), "")

/* Expands to ASSERT_WIDTH(1); ASSERT_WIDTH(2); ...; ASSERT_WIDTH(64); */
#define ASSERT_WIDTH_2(n)  ASSERT_WIDTH(2 * (n) - 1); ASSERT_WIDTH(2 * (n))
#define ASSERT_WIDTH_4(n)  ASSERT_WIDTH_2(2 * (n) - 1); ASSERT_WIDTH_2(2 * (n))
#define ASSERT_WIDTH_8(n)  ASSERT_WIDTH_4(2 * (n) - 1); ASSERT_WIDTH_4(2 * (n))
#define ASSERT_WIDTH_16(n) ASSERT_WIDTH_8(2 * (n) - 1); ASSERT_WIDTH_8(2 * (n))
#define ASSERT_WIDTH_32(n) ASSERT_WIDTH_16(2 * (n) - 1); ASSERT_WIDTH_16(2 * (n))
#define ASSERT_WIDTH_64()  ASSERT_WIDTH_32(1); ASSERT_WIDTH_32(2)
ASSERT_WIDTH_64();

int main(void) {
    int ret[] = {1, 1, 0};
    switch (2) {
        /* Check validity as a constant expression */
        case MAX_TO_WIDTH(3):
            /* Check parenthesization */
            return MAX_TO_WIDTH(3)[ret];
        default:
            return 1;
    }
}

```

The code should compile without errors (warnings are okay), and run successfully (returning 0), without invoking any undefined behaviour. If you save this code as `golf.c`, you can check it like this:

```
user@host$ clang -fsanitize=undefined golf.c -o golf && ./golf || echo FAIL

```

## Scoring

Your score is the **number of preprocessing tokens** that the test code expands to using your `MAX_TO_WIDTH()` definition. Lower scores are better. You can use clang's `-dump-tokens` flag to determine this:

```
user@host$ clang -fsyntax-only -Xclang -dump-tokens golf.c 2>&1 | wc -l
13877

```

This score is insensitive to whitespace, comments, and name length, so there's no incentive to golf the implementation in a way that obfuscates it.

### Extra credit

If you want, you can calculate the largest \\$n\\$ for which your \\$\texttt{MAX\_TO\_WIDTH}(2^n - 1)\\$ would behave correctly (assuming a hypothetical C implementation with \\$n\\$-bit integers). Remember, \\$n\\$ must be at least 128, but it may be (significantly) higher. Each \\$n\\$ defines a "weight class" (so to speak) which includes all submissions with equal or greater \\$n\\$ values. For example, with these submissions:

| Submitter | Score | \\$n\\$ |
| --- | --- | --- |
| A | 12000 | 128 |
| B | 11000 | 256 |
| C | 13000 | 512 |

We'd have a leaderboard like this:

| Weight class | Winner |
| --- | --- |
| \\$n \ge 128\\$ | B |
| \\$n \ge 256\\$ | B |
| \\$n \ge 512\\$ | C |

# Answer
> 3 votes
# n \< 160, score ~~11925~~ 11661

```
#define MAX_TO_WIDTH(x) (~0ull / 31 * ((x) >> 4 & ~0ull / 31 / (~0ull / 31 & 31)) / (~0ull / 32) * 5 + 4 - 12 / (3 + (x) % 31))

```

Try it online! Verify the score!

Explanation: The first part masks out the bits corresponding to `2⁴`, `2⁹`, `2¹⁴` etc., then counts just those bits by multiplying by a shifted mask and shifting. This value is multiplied by `5`. Any remaining bits are extracted via `% 31` and these are counted in a similar way to @TavianBarnes' answer by adding `3` and dividing into `12`. In fact this can be done for any number of bits up to `8` using the Fibonacci numbers:

```
2 - 2 / (1 + (x) % 7)
3 - 6 / (2 + (x) % 15)
4 - 12 / (3 + (x) % 31)
5 - 25 / (5 + (x) % 63)
6 - 48 / (8 + (x) % 127)
7 - 91 / (13 + (x) % 255)

```

For specific values of `n` the score can be reduced by folding the constants.

# n = 128, score ~~10622~~ 10362

```
#define MAX_TO_WIDTH(x) (0x8421084210842108421084210842108ull * ((x) >> 4 & 0x1084210842108421084210842108421ull) / 0x8000000000000000000000000000000ull * 5 + 4 - 12 / (3 + (x) % 31))

```

Can't try it online but Verify the score!

# n = 64, score ~~10473~~ 10209

```
#define MAX_TO_WIDTH(x) (0x1084210842108421ull * ((x) & 0x842108421084210ull) / 0x800000000000000 * 5 + 4 - 12 / (3 + (x) % 31))

```

Try it online! Verify the score!

Edit: Saved a bunch from all the scores by removing ~~a~~ two sets of unnecessary parentheses (in some cases I had to switch a right shift to a divide by a power of `2`).

# Answer
> 2 votes
# Score: ~~13877~~ 13613, \\$n = 2040\\$.

*-264 thanks to l4m2*

```
#define CHUNK(m, mask) (m) / ((m) % mask + 1) / mask % mask
#define INTERP(m) 7 - 86 / ((m) % 255 + 12)
#define MAX_TO_WIDTH(m) (CHUNK(m, 255) * 8 + INTERP(m))

```

---

This idea is due to Hallvard B. Furuseth on a comp.lang.c post in 2003. It uses this helper function

```
#define CHUNK(m, mask) (m) / ((m) % mask + 1) / mask % mask

```

Which is used to make a repeating sequence like this:

$$ \begin{aligned} a\_{i,j} & = \texttt{CHUNK}(2^i - 1, 2^j - 1) \\ a\_{0,j}, a\_{1,j}, a\_{2,j}, \ldots & = \underbrace{0, \ldots, 0}\_{\text{$j$ times}}, \underbrace{1, \ldots, 1}\_{\text{$j$ times}}, \cdots, \underbrace{2^j-2, \ldots, 2^j - 2}\_{\text{$j$ times}}, 0, \ldots \end{aligned} $$

You can play around with it in Python to see:

```
>>> def CHUNK(m, mask):
...     return (m) // ((m) % mask + 1) // mask % mask
...
>>> def a(i, j):
...     return CHUNK(2**i - 1, 2**j - 1)
...
>>> [a(i, 2) for n in range(10)]
[0, 0, 1, 1, 2, 2, 0, 0, 1, 1]
>>> [a(i, 3) for n in range(10)]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3]
>>> [a(i, 4) for n in range(10)]
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2]
>>> [a(n, 5) for n in range(5 * (2**5 - 1))] == \
... [i for i in range(2**5 - 1) for j in range(5)]
True

```

This sequence has \\$j \\, (2^j - 1)\\$ values before it wraps, meaning

$$ \texttt{CHUNK}(2^i - 1, 2^j - 1) = \lfloor i/j \rfloor \quad \text{for all $i \< j \\, (2^j - 1)$.} $$

This is almost enough—what we want is \\$j \\, \lfloor i/j \rfloor + (i \bmod j) = i\\$. We can get \\$(i \bmod j)\\$ in various ways. For now, let's fix \\$j = 8\\$. We know that \\$2^i \pmod {2^8 - 1}\\$ will have period 8:

```
>>> [(2**i - 1) % 255 for i in range(16)]
[0, 1, 3, 7, 15, 31, 63, 127, 0, 1, 3, 7, 15, 31, 63, 127]

```

And we can brute force a linear interpolation of these that maps them to `[0, 1, 2, ...]`:

```
>>> [(7 - 86 // ((2**i - 1) % 255 + 12)) for i in range(16)]
[0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7]

```

---

The original post is more like this:

```
#define CHUNK(m, mask) (m) / ((m) % mask + 1) / mask % mask
#define INTERP(m) 4 - 12 / ((m) % 31 + 3)
#define MAX_TO_WIDTH(m) \
    (CHUNK(m, 0x3fffffffL) * 30 + CHUNK((m) % 0x3fffffff, 31) * 5 + INTERP(m))

```

Which would have score: 21477, \\$n = 30 \cdot (2^{30} - 1) = 32212254690\\$.

---
Tags: math, code-challenge, c, test-battery
---


title: Egyptian fraction representations of 1

text:
# Question
Title: Egyptian fraction representations of 1
An Egyptian fraction is a representation of a rational number using the sum of distinct unit fractions (a unit fraction is of the form \\$ \frac 1 x \\$ where \\$ x \\$ is a positive integer).

For all**\[1\]** positive integers \\$ n \ne 2 \\$, there exists at least one Egyptian fraction of \\$ n \\$ distinct positive integers whose sum is \\$ 1 \\$. For example, for \\$ n = 4 \\$: $$ \frac 1 2 + \frac 1 4 + \frac 1 6 + \frac 1 {12} = 1 $$ Here is another possible output: $$ \frac 1 2 + \frac 1 3 + \frac 1 {10} + \frac 1 {15} = 1 $$

The number of possible outputs is given by A006585 in the OEIS.

**\[1\]**: I cannot find a direct proof of this, but I can find a proven lower bound on A006585, which has this as an obvious consequence. If you can find (or write!) a better / more direct proof that a representation exists for all \\$ n \ne 2 \\$ I would love to hear it.

## Task

Given \\$ n \\$, output a list of positive integers representing the denominators of *at least one* valid solution of length \\$ n \\$.

You may alternatively output a list of rational numbers which are unit fractions, but only if they are an exact representation of the value (so not floating-point).

## Test cases

I only list a few possible outputs. Here is a Ruby program which can verify any solution.

```
n     outputs
1     {1}
3     {2, 3, 6}
4     {2, 4, 6, 12} or {2, 3, 10, 15} or {2, 3, 9, 18} or {2, 4, 5, 20} or {2, 3, 8, 24} or {2, 3, 7, 42} or ...
5     {2, 4, 10, 12, 15} or {2, 4, 9, 12, 18} or {3, 4, 5, 6, 20} or {2, 5, 6, 12, 20} or {2, 4, 8, 12, 24} or {2, 4, 7, 14, 28} or ...
8     {4, 5, 6, 9, 10, 15, 18, 20} or {3, 5, 9, 10, 12, 15, 18, 20} or {3, 6, 8, 9, 10, 15, 18, 24} or {4, 5, 6, 8, 10, 15, 20, 24} or {3, 5, 8, 10, 12, 15, 20, 24} or {4, 5, 6, 8, 9, 18, 20, 24} or ...
15    {6, 8, 9, 11, 14, 15, 18, 20, 21, 22, 24, 28, 30, 33, 35} or {7, 8, 10, 11, 12, 14, 15, 18, 20, 22, 24, 28, 30, 33, 36} or {6, 8, 10, 11, 12, 15, 18, 20, 21, 22, 24, 28, 30, 33, 36} or {6, 8, 10, 11, 12, 14, 18, 20, 21, 22, 24, 28, 33, 35, 36} or {5, 8, 11, 12, 14, 15, 18, 20, 21, 22, 24, 28, 33, 35, 36} or {5, 8, 10, 11, 14, 15, 18, 21, 22, 24, 28, 30, 33, 35, 36} or ...

```

## Rules

* You may output the numbers in any order
* If you choose to output all possible solutions, or a particular subset of them, you must not output duplicates. This includes lists which are the same under some permutation.
* You may assume \\$ n \\$ is a positive integer, and is not \\$ 2 \\$
* Your code does not need to practically handle very high \\$ n \\$, but it must work in theory for all \\$ n \\$ for which a solution exists
* You may use any standard I/O method
* Standard loopholes are forbidden
* This is , so the shortest code in bytes wins

# Answer
> 30 votes
# Python 2, 42 bytes

```
f=lambda n,x=1:1/n*[x]or[x+1]+f(n-1,x*-~x)

```

Try it online!

The key thing to observe is that `1/n = 1/(n+1) + 1/(n*(n+1))`. Therefore we can always obtain a solution with `n` fractions, by using a solution with `n-1` fractions, and "splitting" the last fraction in two.

# Answer
> 13 votes
# Vyxal, 10 bytes

```
¡ɾṗ'Ė∑1=;t

```

Try it Online!

Bruteforcer. \\$O\left(2^{n!}\right)\\$ time complexity, searches for fractions with reciprocals \\$ n! \\$ which seems to be enough.

```
¡          # Factorial
 ɾṗ        # All combinations of 1...n
   '    ;  # Filtered by...
    Ė∑     # Sum of reciprocals
      1=   # is 1?
         t # Get the last one

```

# Answer
> 12 votes
# Wolfram Language (Mathematica), 32 bytes

Using Sylvester's sequence A000058

```
Nest[##&[#^2+#,1+#,##2]&,1,#-1]&

```

Try it online!

-8 bytes from @att

# Answer
> 9 votes
# Factor, 48 bytes

```
[ 1 - 2 [ 3 dupn . sq - abs 1 + ] repeat 1 - . ]

```

Try it online!

Port of @ZaMoC's Mathematica answer. It prints the first n terms of Sylvester's sequence, subtracting 1 from the last number.

The old way that doesn't quite work:

```
[ [1,b] dup 1 rotate v* ]

```

# Answer
> 7 votes
# , ~~44~~ 38 bytes

*-6 bytes thanks to Dominic van Essen*

```
function(n)2^(1:n)*.75^(n:1<3)-(n<2)/2

```

Try it online!

## First Attempt

```
function(n){k<-1:n;2^k*.75^(k>n-2)-(n==1)/2}

```

Try it online!

Port of my Excel answer.

# Answer
> 6 votes
# Ruby, ~~70 40~~ 34 bytes

```
->n{a=1;(2..n).map{a*=q=1+a;q}<<a}

```

Try it online!

Based on dingledooper's python answer. Some bytes saved by following Kevin Cruijssen's advice.

# Answer
> 6 votes
# , ~~55~~ 57 bytes

*Edit: Thanks to Anders Kaseorg (and +2 bytes) for bug-spotting*

```
function(n){while(n<-n-1)T=c((k=T[1]+1)*T[1],k,T[-1]);+T}

```

Try it online!

Outputs one egyptian fractional representation of 1 using n fractions, constructed using ZaMoC's & dingledooper's approach.

---

# , 102 bytes

```
function(n,m=n){while(all(F<-apply(l<-combn(1:m,n),2,function(k)sum(prod(k)/k)-prod(k))))m=m+1;l[,!F]}

```

Try it online!

A brute-force approach that outputs the egyptian fractional representation(s) with the lowest-valued top denominator, by trying all combinations of fractions up to successively increasing denominators.

# Answer
> 5 votes
# Charcoal, 16 bytes

```
ＦＮ⊞υ⊕∨Πυ¹⊞υ⊖⊟υＩυ

```

Try it online! Link is to verbose version of code. Explanation: Uses a formula for Sylvester's sequence taken from A000058.

```
ＦＮ

```

Loop `n` times...

```
⊞υ⊕∨Πυ¹

```

... push the incremented product of the list to the list. (Note that the version of Charcoal on TIO can't take the product of an empty list, so I have to manually replace the result with `1`.)

```
⊞υ⊖⊟υ

```

Decrement the last element of the list.

```
Ｉυ

```

Output the list.

14 bytes using the newer version of Charcoal on ATO that can take the product of an empty list:

```
ＦＮ⊞υ⊕Πυ⊞υ⊖⊟υＩυ

```

Attempt This Online! Link is to verbose version of code.

# Answer
> 5 votes
# Excel, 47 bytes

```
=LET(x,SEQUENCE(A1),0.75^(x>A1-2)*2^x-(A1=1)/2)

```

Link to Spreadsheet

Uses the fact that for \\$ n\>2\\$: $$\sum\_{k=1} ^{n-2} \left(\frac 1 {2}\right) ^ k + \frac 4 {3}\left(\left(\frac 1 {2}\right)^{n-1} + \left(\frac 1 {2}\right)^n\right) = 1$$.

# Answer
> 5 votes
# tinylisp, ~~106~~ ~~105~~ 98 bytes

```
(load library
(d g(q((n x)(i(e n 1)x(g(s n 1)(c(*(a(h x)1)(h x))(c(a(h x)1)(t x
(d f(q((n)(g n(q(1

```

Try it online!

Not sure there's a better way to ~~get `(1)` than `(c 1()`~~ (use `(q(1`) add two elements to a list than `(c X(c Y Z)`.

Ports e.g., Dominic van Essen's R answer.

Thanks to DLosc for -5 bytes.

# Answer
> 4 votes
# Jelly, ~~10~~ 9 bytes

```
⁸P‘ṭƊ¡’0¦

```

Try it online!

Based on the Sylvester sequence.

# Answer
> 4 votes
# tinylisp, ~~156~~ ~~97~~ 91 bytes

*-59 bytes remove extra spaces and use pow function*

*-6 bytes thanks to @DLosc*

```
(load library
(d g(q((n m)(i m(c(/(*(s 4(l(s n 2)m))(pow 2 m))4)(g n(s m 1)))(
q((n)(g n n

```

Try it online!

## First Attempt

```
(load library
(d p(q((x n)(i n(* x(p x(s n 1)))1
(d g(q((n m)(i m(c(/(*(i(l m (s n 1))4 3)(p 2 m))4)(g n(s m 1)))(
(d f(q((n)(g n n

```

Try it online!

Porting into tinylisp.

# Answer
> 3 votes
# Pari/GP, 34 bytes

```
n->[q-(i==n)|i<-[a=1..n],a*=q=1+a]

```

Try it online!

A port of @ZaMoC's Mathematica answer and @G B's Ruby answer.

# Answer
> 3 votes
# 05AB1E, ~~13~~ 9 bytes

```
$GD>DŠ*})

```

-4 bytes porting *@GB*'s Ruby answer.

Try it online or verify the first \\$n=10\\$ test cases, excluding \\$2\\$.

Alternative 9-byter inspired by *@Neil*'s comment below, which is pretty similar as the current approach above:

```
$EPNIÊ+ˆ¯

```

Try it online or verify the first \\$n=10\\$ test cases, excluding \\$2\\$.

**Explanation:**

```
$         # Push 1 and the input-integer
 G        # Loop input-1 amount of times:
  D       #  Duplicate the current integer
   >      #  Increase this copy by 1
    D     #  Duplicate that as well
     Š    #  Tripleswap the stack from a,b,c to c,a,b
      *   #  Multiply the top two values
 })       # After the loop, wrap all values on the stack into a list
          # (after which the result is output implicitly)

$         # Push 1 and the input-integer
 E        # Loop `N` in the range [1,input]:
  P       #  Push the product of the stack / top
          #  (which will be 1 in the first iteration)
   NIÊ    #  Check that `N` is NOT equal to the input
          #  (0 if it's the final iteration, 1 otherwise)
      +   #  Add that to the product
       ˆ  #  Pop and add it to the global array
        ¯ #  Push the global array for the next iteration
          # (after which the last pushed global array is output implicitly after
          # the loop)

```

# Answer
> 3 votes
# JavaScript (Node.js), ~~53~~ 52 bytes

```
f=(n,x=1)=>[,[x],[x*3,x*1.5]][n]||[x*=2,...f(n-1,x)]

```

Try it online!

Making special \\$1=\frac 13+\frac 1{1.5}\\$ make it bit shorter

# Answer
> 2 votes
# Python 2, 43 bytes

*-10 bytes thanks to dingledooper*

```
lambda n:[4-(x>n-3)<<x>>1for x in range(n)]

```

Try it online!

## First Attempt, 53 bytes

```
f=lambda n:map(lambda x:2**x*(4-(x>n-3))/2, range(n))

```

Try it online!

Porting to Python.

# Answer
> 2 votes
# APL(Dyalog Unicode), 26 bytes SBCS

```
{1≡⍵:1⋄3≡⍵:2 3 6⋄2,2×∇⍵-1}

```

Try it on APLgolf!

A dfn submission which encodes the inductive proof posted in the comments: to get a solution for `n+1`, double each of the denominators and add `2` to the denominators.

E.g. `2 3 6` solves `3``2 4 6 12` solves `4``2 4 8 12 24` solves `5` → ...

# Answer
> 2 votes
# JavaScript, 48 bytes

Try it online

```
f=n=>--n>1?[1,...f(n)].map(x=>x*2):n?[1.5,3]:[1]

```

Original answer (49 bytes):

```
f=n=>[[1],,[2,3,6]][--n]||[2,...f(n).map(x=>x*2)]

```

# Answer
> 1 votes
# Scala, 105 bytes

Golfed version. Try it online!

```
def f(n:Int)=(1 to n).map(i=>{var a,q=BigInt("1");for(_<-1 to i){a*=q;q=1+a};q-(if(i==n)1 else 0)}).toSeq

```

Ungolfed version. Try it online!

```
object PariGpInScala {
  def main(args: Array[String]): Unit = {
    val inputList = List(1, 3, 4, 5, 6, 7, 8, 9, 10)

    inputList.foreach { n =>
      println(s"$n summands:")
      println(s"1 = ${f(n).map(x=>"1/"++x.toString)mkString(" + ")} \n")
    }
  }

  def f(n: Int): List[BigInt] = {
    (1 to n).map { i =>
      var a,q = BigInt("1")
      for (_ <- 1 to i) {
        a *= q
        q = 1 + a
      }
      q - (if (i == n) 1 else 0)
    }.toList
  }
}

```

# Answer
> 0 votes
# APL(NARS), 80 chars

```
r←z w;k;t
r←⍬⋄→0×⍳2≥w⋄r←2 3 6
→3×⍳w=k←≢r⋄t←r[k]÷6⋄r[k]←t×t+6⋄r,←6×t+6⋄→2
r←r[⍋r]

```

10+20+43+7=80. It return ⍬ if w≤2, 2 3 6 if w=3, otherwise it use the formula

```
1/r*s=(1/(r*(r+s)))+(1/s*(r+s))

```

for make more long the array of start 2 3 6. z has the peculiarity could calculate easly the result at last for argument \<= 20000, because the numbers are not big numbers there will be a problem for the argument too much big, when `r*(r+s)` or `s*(r+s)` will be too much big.

```
  z 3
2 3 6
  z 2

  z 4
2 3 7 42
  z 20
2 3 7 91 247 475 618 775 1147 1591 2107 2695 3355 4087 4891 5767 6715 7735 8827 9991
  +/÷z 20
1
  +/÷z 20000
1

```

---
Tags: code-golf, math, number-theory, rational-numbers, open-ended-function
---


title: Legen… wait for it…

text:
# Question
Title: Legen… wait for it…
# dary!

In events entirely unrelated to what will hopefully happen to me in the next couple of days, I task you to write code that does the following:

1. Print

```
Legen... wait for it...

```

immediately, with a trailing newline.
2. Wait until the next full hour (when the cron job for awarding the badge runs).
3. Print

```
dary!

```

with an *optional* trailing newline.

### Additional rules

* You may write a program or a function, but the output has to be printed to STDOUT (or its closest alternative of your language).
* You have to wait until the next *full* hour, not just for 60 minutes. If the code is run at 6:58, it should print the second line at 7:00.
* The last line must be printed no later than one second after the next full hour.
* In the event that the program is started in the first second of a full hour, it should it wait for the next full hour.
* You may query local or UTC time.
* Standard rules apply.

# Answer
# Pyth, ~~42~~ 41

```
J.d6." wâ«hÖ`Ùá©h´^"WqJ.d6;"dary!

```

Below is a hexdump of the code:

```
00000000  4a 2e 64 36 2e 22 20 77  0c 10 89 e2 ab 1b ad 68  |J.d6." w.......h|
00000010  0f 8c d6 60 d9 e1 a9 68  82 b4 5e 22 57 71 4a 2e  |...`...h..^"WqJ.|
00000020  64 36 3b 22 64 61 72 79  21                       |d6;"dary!|

```

Saved 1 byte thanks to @isaacg

Uses the `.d` function to get local time related values. `.d6` returns the current hour. This prints the first string, then waits until the hour is different from the hour ad the start of the program, and then prints the second string.

You could try it online with `.d7` or `.d8` for minutes/seconds but the online compiler only prints anything when the program terminates.

Congrats, Dennis! :)
> 12 votes

# Answer
# JavaScript (ES6), 74 bytes

You may want to change your system clock before testing, congratulations if you landed here at 59 minutes past.

```
setTimeout(a=alert,36e5-new Date%36e5,"dary!");a`Legen... wait for it...
`
```
> 27 votes

# Answer
## CJam, ~~49~~ 48 bytes

```
et3="Legen... wait for it...
"o{_et3==}g;"dary!"

```

Uses local time. For testing purposes, you can replace the two instances of `3` with `4` or `5` to make it print at the start of the next minute/second.

Test it here. But note that the online interpreter doesn't show any output until the program terminates. Alternatively, you can run it on Try it online, where the output is shown *almost* immediately instead of being buffered (but when you test it with seconds instead of hours, the delay will be noticeable). In any case, if you run it locally with the Java interpreter, it works like a charm.

### Explanation

This makes use of CJam's `et` which gives you an array of

```
[year month day hour minute second ms weekday utc_offset]

```

Here is a breakdown of the code:

```
et3=       e# Get the current hour.
"Legen..." e# Push the first string including the linefeed.
o          e# Print it.
{          e# While the top of stack is truthy (which is popped)...
  _        e#   Copy the original hour.
  et3=     e#   Get the current hour.
  =        e#   Check for equality.
}g
;          e# Discard the original hour.
"dary!"    e# Push the second string which is printed automatically.

```

### Bonus

This also works for the same byte count:

```
et4<"Legen... wait for it...
"o{et1$#!}g;"dary!"

```

Instead of selecting the hour, we're selecting the prefix with the date *and* the hour, and keep the loop going while the datetime array still has that prefix.
> 9 votes

# Answer
# AppleScript, ~~157~~ 149 bytes

Huh. Surprisingly contending.

```
set d to number 1 in time string of(current date)
log"Legen... wait for it..."
repeat while d=number 1 in time string of(current date)
end
log"dary!"
```

Since `log` prints to the Messages pane of Script Editor, I consider it to be the closest output to STDOUT. Basically, if you get the time string of current date, it'll do something like this:

Code:

```
time string of(current date)
```

Output:

```
5:02:03 PM
```

It will grab the first number (`5`) before the colon.

I thought it'd be a lot longer than this, actually. xD
> 9 votes

# Answer
## Snowman 1.0.2, ~~70~~ 69 bytes

```
~"Legen... wait for it...
"sP3600000*vt#nDnC!*:vt+#nD!#nL;bD"dary!"sP

```

Explanation:

```
~              Make all variables active.
"..."sP        Print the first string.
3600000*vt#nD  Get the number of hours since the Unix epoch.
nC             Ceiling (round up), giving the time (divided by 36000) at which to
                 print the second string.
!*             Save that in a permavar.
:...;bD        Do the stuff in the block while its "return value" is truthy.
  vt+#nD       Again, get the number of hours since epoch.
  !#             Store the permavar that we saved earlier.
  nL             Is the current time less than the target time? (if so,
                   keep looping)
"..."sP        Print the second string.

```
> 8 votes

# Answer
# PHP, 76, 70, 65, 62 51 bytes

```
Legen... wait for it...
<?while(+date(is));?>dary!

```

Previous logic (63b):

```
Legen... wait for it...
<?for($h=date(G);date(G)==$h;)?>dary!

```

This kind of coding makes you loose your job, but this loops until the time is 1 hour further than init.

-1 byte by replacing `{}` afer the while to `;` (thanks manatwork)
-5 bytes by replacing `echo'dary!';` to `?>dary!` (thanks manatwork)
-4 bytes by replacing `<?php` to the short version `<?` (thanks primo)
-1 byte by replacing the `while` for a `for`
-3 bytes by replacing `date(G)!=$h+1` to `date(G)==$h` (thanks primo)
> 7 votes

# Answer
## Perl 6, 60 bytes

```
sleep 60²-now%60²+say 'Legen... wait for it..';say 'dary!'

```
> 7 votes

# Answer
# Javascript 94 90 87 bytes

Not golfed that much...

```
alert`Legen... wait for it...`,l=l=>~~(Date.now()/36e5);for(z=l();z==l(););alert`dary!`

```

Downgoat's version:

```
(a=alert)`Legen... wait for it...`,z=(b=new Date().getHours)();for(;z==b(););a`dary!`

```

It stores the current hour and loops for as long as the "old" hour is equal to the current one. As soon as the hour has changed, it will print the rest! :D

Disclaimer: If your browser dislikes it, you have been warned.
> 5 votes

# Answer
# Python 2, ~~82~~ 81 bytes

```
from time import*;print'Legen... wait for it...';sleep(-time()%3600);print'dary!'

```

Too low a reputation to comment. Python 2 version of Alexander Nigl's solution. Saves characters lost on brackets. Also, 3600 not needed in the sleep time calculation.

7 characters saved overall.

Edit: -1 byte thanks to @Kevin Cruijssen
> 5 votes

# Answer
## Mathematica, ~~85~~ ~~84~~ 81 bytes

```
c=Print;c@"Legen... wait for it...";a:=DateValue@"Hour";b=a;While[a==b];c@"dary!"

```
> 4 votes

# Answer
# MATLAB - 89 bytes

```
a=@()hour(now);disp('Legen... wait for it...');while(mod(a()+1,24)~=a())end;disp('dary!')

```

Pretty self-explanatory. First, create a function handle to grab the current hour of the system clock. Then, display `Legen... wait for it...` with a carriage return, and then we go into a `while` loop where we keep checking to see if the current hour added with 1 is **not** equal to the current hour. If it is, keep looping. Only until the instant when the next hour happens, we display `dary!` and a carriage return happens after.

MATLAB's hour is based on 24-hour indexing, so the `mod` operation with base 24 is required to handle spilling over from 11 p.m. (23:00) to midnight (00:00).

## Minor Note

The `hour` function requires the Financial Time Series toolbox. The `now` function is not subject to this restriction, but it retrieves the current date and time as a serial number which `hour` thus uses to compute the current hour.

## Want to run this in Octave?

Sure! Because Octave doesn't have this toolbox, we'd just have to modify the `hour` function so that it calls `datevec` which returns a vector of 6 elements - one for each of the year, month, day, hour, minutes and seconds. You'd just have to extract out the fourth element of the output:

```
a=@()datevec(now)(4);disp('Legen... wait for it...');while(mod(a()+1,24)~=a())end;disp('dary!')

```

The additional characters make the solution go up to 98 bytes, but you'll be able to run this in Octave. Note the in-place indexing without a temporary variable in the function handle.

# No Financial Time Series Toolbox?

If you want to run this in MATLAB **without** the Financial Time Series Toolbox, because you can't index into variables immediately without at temporary one, this will take a bit more bytes to write:

```
disp('Legen... wait for it...');h=datevec(now);ans=h;while(mod(h(4)+1,24)~=ans(4)),datevec(now);end;disp('dary!');

```

This first obtains the current time and date and stores it into the variable `h` as well as storing this into the automatic variable called `ans`. After, we keep looping and checking if the current hour isn't equal to the next hour. At each iteration, we keep updating the automatic variable with the current time and date. As soon as the next hour matches with the current time and date, we display the last part of the string and quit. This pushes the byte count to 114.

---

Also take note that you can't try this online. Octave interpreters online will have a time limit on when code executes, and because this is a `while` loop waiting for the next hour to happen, you will get a timeout while waiting for the code to run. The best thing you can do is run it on your own machine and check that it works.
> 4 votes

# Answer
# C, 163 bytes

```
#include<time.h>
f(){puts("Legen... wait for it...");time_t t=time(0);struct tm l=*localtime(&t);while(l.tm_min+l.tm_sec)t=time(0),l=*localtime(&t);puts("dary!");}

```
> 4 votes

# Answer
# Microscript II, 45 bytes

```
"Legen... wait for it..."P[36s5E*sD%_]"dary!"

```

Finally, a use for the `D` instruction.

Prints the first string, repeatedly takes the UTC time in milleseconds modulo 3,600,000 until this yields 0, and then produces the second string which is printed implicitly. The 3,600,000 is represented in the code as 36x105.
> 3 votes

# Answer
## TI-BASIC, ~~70~~ 64 bytes

```
getTime
Disp "Legen... wait for it...
Repeat sum(getTime-Ans,1,1
End
"dary

```

*Curse these two-byte lowercase letters!*

`getTime` returns a three-element list `{hours minutes seconds}`, so the sum from the 1st element to the 1st is the hours. When there is a difference between the hours at the start and the current hours, the loop ends. Thanks to @FryAmTheEggman for this observation.
> 3 votes

# Answer
# R - 97 bytes

```
cat('Legen... wait for it...\n')
Sys.sleep(1)
while(as.double(Sys.time())%%3600>0){}
cat('dary!')

```
> 3 votes

# Answer
# Perl, 62 bytes

```
sleep -++$^T%3600+print'Legen... wait for it...
';print'dary!'

```

The special variable `$^T` (a.k.a `$BASETIME`) records the number seconds since epoch from when the script was started. Fortunately, leap seconds are not counted in the total, so that the following are equivalent:

```
print$^T%3600;
@T=gmtime;print$T[1]*60+$T[0];

```

Surprisingly, this variable is not read-only.
> 3 votes

# Answer
# Python 3 - 92 89 bytes

```
from time import*;print("Legen... wait for it...");sleep(3600-time()%3600);print("dary!")

```
> 3 votes

# Answer
# Japt, ~~72~~ 61 bytes

```
`{?tT?e?t(Ã?t,36e5-?w D?e%36e5,'ÜÝ!'),'Leg?... Ø2 f? ?...\n'}

```

Each `?` represents a Unicode unprintable char. Here's how to obtain the full text:

1. Open the online interpreter.
2. Paste this code into the Code box:

```
Oc"`\{setTimeout(alert,36e5-new Date%36e5,'dary!'),'Legen... wait for it...\\n'}

```
3. Run the code, then erase it from the Code box.
4. Select the contents of the Output box and **drag** to the Code box. **Copy-pasting will not work**.
5. Replace the first space with a non-breaking space.
6. (optional) Set your computer's clock to xx:59.
7. Run the code.

Alternatively, here is a (hopefully reversible) hexdump:

```
00000000: 607b a074 548b 658c 7428 c300 742c 3336 65    `{ tT?e?t(Ã?t,36e
00000011: 352d 9a77 2044 8565 2533 3665 352c 27dc dd    5-?w D?e%36e5,'ÜÝ
00000022: 2127 293b 274c 6567 812e 2e2e 20d8 3220 66    !'),'Leg?... Ø2 f
00000033: 8e20 8a2e 2e2e 5c6e 277d                      ? ?...\n'}

```

This code is based on George Reith's JavaScript answer, with a few Japt-specific changes. I found out the other day that if you compress code and insert it into a backtick-wrapped string, it will automatically decompress. Here's how it's processed through compilation:

```
`{?tT?e?t(Ã?t,36e5-?w D?e%36e5,'ÜÝ!'),'Leg?... Ø2 f? ?...\n'}
"{setTimeout(alert,36e5-new Date%36e5,'dary!'),'Legen... wait for it...\n'}"
""+(setTimeout(alert,36e5-new Date%36e5,'dary!'),'Legen... wait for it...\n')+""

```

In JS, a pair of parentheses will return the last value inside; thus, this code sets the timed event, then returns the `'Legen...'` string, which is automatically sent to STDOUT. Since Japt currently has no way to add content to STDOUT other than automatic output on compilation, I've instead used the vanilla JS function `alert` for the timed output. I hope this is allowed.
> 2 votes

# Answer
# Windows Command Script, 87 bytes

```
@set.=%time:~,2%&echo.Legen... wait for it...
:.
@if %.%==%time:~,2% goto:.
@echo.dary!

```

This continually compares an hour-variable stored at start against the current hour and succeeds if different.
> 2 votes

# Answer
# Jelly,  ~~48 47~~  45 bytes

-1 byte thanks to Erik the Golfer (use "Leg" as a word in the compression)
-2 thanks to caird coinheringaahing

```
“ÇỴġƒḃhlḂṀ⁷*Ḣ¡w*Jḷv»Ṅø3ŒTṣ”:V59_ḅ60‘œS@“dary!

```

**Try it online!** Or run a test version with a hard coded time-formatted-string of `“59:57”` ("mm:ss"). (Note: TIO buffers output, but local runs work as expected.)

There is, at the time of writing, only one way to access the time which is by way of a formatted string, `ŒT`.

This code calculates how long to wait and then sleeps. If called at `hh:00:00` it waits for `3600` seconds: it converts `"00:00"` to `[0,0]` then subtracts that from `59` to yield `[59,59]`, converts that from base sixty to give `3599`, then adds one for a total wait period of `3600` seconds.

Maybe a loop could be made; or a compressed string using the whole word "Legendary" could be utilised somehow?

```
“ÇỴġƒḃhlḂṀ⁷*Ḣ¡w*Jḷv»Ṅø3ŒTṣ”:V59_ḅ60‘œS@“dary! - Main link: no arguments
“ÇỴġƒḃhlḂṀ⁷*Ḣ¡w*Jḷv»                          - compressed "Legen... wait for it..."
                    Ṅ                         - print z + '\n', return z
                     ø                        - niladic chain separation
                      3ŒT                     - '011' (3) time formatted string = "mm:ss"
                         ṣ”:                  - split on ':' -> ["mm","ss"]
                            V                 - eval -> [m,s]
                             59_              - subtract from 59 - > [59-m, 59-s]
                                 ḅ60          - convert from base 60 -> 60*(59-m)+(59-s)
                                    ‘         - increment -> 60*(59-m)+(59-s) = y
                                       “dary! - "dary!" = x
                                     œS@      - sleep y seconds then return x
                                              - implicit print

```
> 2 votes

# Answer
# Powershell, ~~52~~ 51 bytes

*-1 byte thanks @Veskah*

```
'Legen... wait for it...'
for(;Date|% M*e){}'dary!'

```

This expression `Date|% M*e` gets value from `Minute` property from the Current DateTime value. The loop ends when `Minute` equal to 0.
> 2 votes

# Answer
# Befunge 98 - ~~69~~ 63 bytes

```
 v
v>a"...ti rof tiaw ...negeL<ETB>"k,
>"EMIT"4(MS+_"!yrad"5k,@

```

The code contains one unprintable character (represented by `<ETB>` as unprintables don't seem to show up in code blocks). Its character code is 23 (an End transmission block character).

Warning: The preceding code will run in a busy loop with the stack getting bigger each repetition and thus may consume large amounts of memory.
> 1 votes

# Answer
## Python, 112 bytes

```
import time as t;print "Legen... wait for it...";n=t.ctime();t.sleep((60-n.tm_min)*60+60-n.tm_sec);print "dary!"

```

Pretty self explanatory.
> 1 votes

# Answer
## Python - 159 bytes

```
from datetime import*;from threading import*;p=print;n=datetime.now();p('Legen... wait for it...');Timer(3600-(n.minute*60+n.second),lambda:p('dary!')).start()

```
> 1 votes

# Answer
# Mouse-2002, 62 bytes

Requires the user to press enter. I think.

```
"Legen... wait for it..."?&HOUR 1+x:(&HOUR x.=["dary"33!'0^])

```

---

Okay, well, while we're taking lots of bytes and not winning anything, let's have a little fun.

```
"Legen... wait for it... "?     ~ print & require keypress

&HOUR 1+ x:                     ~ get hr, add 1 and assign
(                               ~ while(1)
  &HOUR x. =                    ~ cmp current hr, stored hr
  [                             ~ if same
    #B;                           ~ backspace
    "dary"36!'                    ~ print this string and a !
    0^                            ~ exit cleanly
  ]                             ~ fi
  &MIN 59 - &ABS !              ~ get min, subtract from 59, abs & print
  ":"                           ~ record sep
  &SEC 59 - &ABS !              ~ same for second
  #B;                           ~ backspace
)
$B 8!' 8 !' 8 !' 8 !' 8 !'@     ~ backspace 5*
$                               ~ \bye

```

Sample:

```
$ mouse legend.m02
Legen... wait for it... 20:32

```

See, it's an updating-in-place countdown timer to the next hour! It makes good use of the while loop, which even doing nothing at all will occupy a core.
> 1 votes

# Answer
# BASIC, 90 bytes

```
Print"Legen... wait for it...":x$=Left(Time,2):Do:Loop Until x$<>Left(Time,2):Print"dary!"

```

Straightforward, golfed using the type prefixes and the implicit `End` statement. Cost is that it works only in FreeBasic dialect `fblite`.
> 1 votes

# Answer
# MathGolf, 39 bytes

```
"Legen... wait for it..."pÆt♪/╚÷▼"dary!

```

Try it online!

Almost beat pyth...

## Explanation

```
Æ     ▼  Repeat the next 5 characters while false
 t       push unix time in milliseconds
  ♪/     divide by 1000
    ╚÷   check if divisible by 3600 (tio solution has 3 in its place)

```
> 1 votes

# Answer
# Vyxal `o`, 36 bytes

```
`Le₁ǐ... ʁṁ λ⟑ it...`,kḢ{:kḢ=|}`d₴⁼!

```

Don't Try it Online!

In the online interpreter, all output happens at once, so you can't see exactly what's happening. However, if you download and run the interpreter, you can see that it functions as expected.

Explanation:

```
`Le₁ǐ... ʁṁ λ⟑ it...`                # Dictionary-compressed string "Legen... wait for it..."
                     ,               # Print with newline
                      kḢ{:kḢ= }      # While the current hour hasn't changed:
                             |       #  Do nothing
                               `d₴⁼! # Dictionary-compressed string "dary!"
                                     # "o" flag - Force implicit output

```
> 1 votes

# Answer
# Pyth - 36 bytes

Waits till the minutes is 0 with a while loop.

```
"Legen... wait for it..."W.d7)"dary!

```
> 0 votes

# Answer
# Java, 136 bytes

```
class a{void A(){System.out.println("Legen... wait for it...");while(System.currentTimeMillis()%3600000!=0);System.out.print("dary!");}}

```

How many milliseconds passed since the last full hour is the result of `System.currentTimeMillis()` mod 3,600,000.

The equivalent monolithic program is 159 bytes long:

```
interface a{static void main(String[]A){System.out.println("Legen... wait for it...");while(System.currentTimeMillis()%3600000!=0);System.out.print("dary!");}}

```
> 0 votes

# Answer
## QBIC, 58 bytes

```
?@Legen... wait for it...|#Dary!|{~mid$$|(_d,4,2)=@00||_XB

```

Explanation

```
?@Legen... wait for it...|     Define string literal "Leg[..]it..." and print it
#Dary!|                        Define string B as "Dary!", but don't use it yet
{                              Opens an indefinite DO loop
~mid$$|(...)=@00|              Translates to IF MID$(...) = C$, where C$ is "00"
    The MID$ takes two characters, starting from pos 4, from the system's time (_d)
    So, if the string "11:00" has "00" starting at pos 4,
_XB                            Terminate the program and print string B
(The DO loop and the IF are closed implicitly)

```
> 0 votes

# Answer
# C#, 119 Bytes

Golfed:

```
var d=DateTime.Now;Console.Write("Legen... wait for it...");while(DateTime.Now.Hour!=d.Hour+1){}Console.Write("dary!");

```

Only needs `using System;` to run - I will add this into the byte count if it's required.

Outputs:

```
"Legen... wait for it..."

```

*(Still waiting for the "dary!" to appear...)*
> 0 votes

# Answer
# Pascal (FPC), 125 bytes

```
Uses sysutils;var t:real;begin t:=Now;writeln('Legen... wait for it...');while trunc(t*24)=trunc(Now*24)do;write('dary!')end.

```

Try it online! (Wait for the next minute version)

After digging through FPC's source code, I learned that return type of `Now()` (and `Time()` and `Date()`) is `TDateTime` which is the same as `Double` and `Real` and that the whole part is used for the date and the fractional part is used for the time. Multiplying `Now()` by 24 gives the number of hours in the whole part. The program saves the current time in `t` at the start and waits until the mutiplied whole part changes (by comparing truncated values).
> 0 votes

# Answer
# Ruby, 66 bytes

Very straight forward, i guess

`puts"Legen... wait for it...";sleep 60.*60-Time.now.min;puts:dary!`
> 0 votes

# Answer
# C (Windows API), 119 bytes

```
#include <Windows.h>
WORD s[8];main(){puts("Legen... wait for it...");do{GetLocalTime(s);}while(s[6]!=0);puts("dary!");}

```
> 0 votes

# Answer
# Bean, 58 bytes

### Hexdump:

```
00000000: a653 d080 a038 2080 4023 8100 35cc d420  ¦SÐ. 8 .@#..5ÌÔ
00000010: 218f 2581 0126 2381 02cc e5e7 e5ee aeae  !.%..&#..Ìåçåî®®
00000020: aea0 f7e1 e9f4 a0e6 eff2 a0e9 f4ae ae2e  ® ÷áéô æïò éô®®.
00000030: b3ae b6e5 36e4 e1f2 f921                 ³®¶å6äáòù!

```

Bean Interpreter

### Equivalent JavaScript (66 bytes):

```
console.log("Legen... wait for it...")
while(new Date%36e5)"dary!"

```

On the Bean Interpreter, make sure not to run without `Multithread` enabled or you might crash your browser. If it's enabled you should have nothing to worry about though, as it runs the blocking `while` loop in a Web Worker.
> 0 votes

# Answer
## F#, 117 bytes

```
let n()=System.DateTime.Now.Hour
let l=
 printfn"Legen... wait for it..."
 let o=n()
 while n()=o do()
 printf"dary!"

```

The brackets after the `n` turns it from a value into a function, so it will be re-evaluated every time it's accessed. Other than that, it's a fairly straight-forward `while` loop.
> 0 votes

# Answer
# SmileBASIC, ~~69~~ ~~66~~ 62 bytes

```
?"Legen... wait for it...
TMREAD OUT,M,
WAIT(60-M)*3600?"dary!

```
> 0 votes

# Answer
# 05AB1E, ~~34~~ 37 bytes

```
”ëÃ!”2ä©н…šÏ€‡€•‚…...«ðý,[žbžc+_#}®θ,

```

+3 bytes because I forgot about rule "*In the event that the program is started in the first second of a full hour, it should wait for the next full hour.*".

Try it online (with the waiting put under a setting).

**Explanation:**

```
”ëÃ!”              # Push Titlecase dictionary word: "Legendary!"
     2ä            # Split it into two equal parts: ["Legen","dary!"]
       ©           # Save this list in the register (without popping)
н                  # Pop and only leave the first value: "Legen"
 …šÏ€‡€•           # Push three space-delimited dictionary words: "wait for it"
        ‚          # Pair them together: ["Legen","wait for it"]
         …...      # Push string "..."
             «     # Append them after each item: ["Legen...","wait for it..."]
              ðý   # Join by spaces: "Legen... wait for it..."
                ,  # Print with a trailing newline
[       }          # Start an infinite loop
 žb                #  Push the current minutes
   žc+             #  Add the current seconds
      _            #  Check if the minutes and seconds combined are exactly 0
       #           #  And if they are 0: stop the infinite loop
®                  # Push the list from the register again
 θ                 # Pop and only leave the last value: "dary!"
  ,                # Print it with trailing newline

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `”ëÃ!”` is `"Legendary!"` and `…šÏ€‡€•` is `"wait for it"`.
> 0 votes

# Answer
# Japt, 38 bytes

```
ÈKc ªKb ªOo`ÜÝ`}fOp`Leg... Ø2 fŽ Š...

```

Try it online!

This program will pause the tab till the hour is reached on Shaggy's intepreter, so it is hosted on tio.

Since Shaggy did most of the work on this one, I'll try to give as best an explanation as possible.

Proof of Concept

## Explanation

```
ÈKc ªKb ªOo`ÜÝ`}fOp`Leg�.. Ø2 fŽ Š..
È              }                                    create a function with 3 params
                f                                   and call it with the following param till falsy
                 Op`Leg�.. Ø2 fŽ Š.. print first part "Legen..
                                                    (returns undefined)
 Kc ªKb ª                                           are current minute and second falsy?
         Oo`ÜÝ`                                     If so, print ..dary!
                                                    (returns undefined, falsy)

```
> 0 votes

# Answer
# CJam, 48 bytes

```
"Legen... wait for it...
"oet3={_et3==}g;"dary!"

```

Try it online! Or don't. Try this version online instead, because it only waits for the *minute* to change.
> 0 votes

# Answer
## Pascal, 154 B

This full `program` requires a processor compliant with ISO standard 10206 “Extended Pascal”, in particular the time related features are necessary. The program performs a busy wait until the hour of *t* differs from the hour of *t0* (to save space called `s`).

```
program b(output);var t,s:timeStamp;begin
getTimeStamp(s);writeLn('Legen... wait for it...');repeat
getTimeStamp(t)until s.hour<>t.hour;write('dary!')end.

```

Degolfed:

```
program legendaryPascal(output);
    var
        start, now: timeStamp;
    begin
        getTimeStamp(start);
        writeLn(output, 'Legen... wait for it...');

        { NB: The `timeValid` test has been omitted from the golfed version. }
        repeat
        begin
            getTimeStamp(now)
        end
        until false in [start.timeValid, now.timeValid, start.hour = now.hour];

        writeLn(output, 'dary!')
    end.

```

See also the Delphi‑esque FreePascal submission, a non‑standardized yet popular Pascal dialect.
> 0 votes

# Answer
# Swift, 119 bytes

```
import Foundation
puts("Legen... wait for it...")
while Calendar.current.component(.minute,from:.now)>1{}
puts("dary!")

```

Fairly self-explanatory. Since we're `import`ing `Foundation` anyway, we can use the `puts` function from C instead of Swift's own `print` function to save 2 bytes.
> 0 votes

---
Tags: code-golf, date
---


title: Integer to string with given radix

text:
# Question
Title: Integer to string with given radix
Write the shortest function to convert an integer into a numeric representation given a radix between 2 and 62. e.g.:

```
to_string(351837066319, 31) => "codegolf"

```

# Answer
> 5 votes
# Python - 86

```
from string import*
def t(n,r,s=''):
 while n:s=printable[n%r]+s;n/=r
 return s or'0'

```

Credit due to Hoa Long Tam for the string import trick

# Answer
> 4 votes
## dc - 43 chars

```
[sb[58-]s_[lb~dZ39*+dB3<_9+rd0<xrP]dsxxk]sf

```

We can shorten this a little if we assume the stack contains only the two arguments.

```
[[58-]s_dSb~dZ39*+dB3<_9+SadLbr0<fLaPc]sf

```

As a standalone program, we only need 37 characters:

```
?o[58-]s_[O~dZ39*+dB3<_9+rd0<xrP]dsxx

```

Instead of using `[39+]sz9<z`, we simply use `Z39*+`, which will add 39 for a single digit number, and 78 for a double digit number. Instead of `113`, we use `B3` (`AD` also works).

# Answer
> 4 votes
# Ruby 1.8 - 75 characters, with recursion.

```
f=proc{|n,b|(n<b ? "":f[n/b,b])+([*'0'..'9']+[*'a'..'z']+[*'A'..'Z'])[n%b]}

```

### Without recursion

```
f=proc{|n,b|d=[*'0'..'9']+[*'a'..'z']+[*'A'..'Z'];s=d[n%b];s=d[n%b]+s while(n/=b)>0;s}

```

(both based on Dogbert's 1.9 solution.)

# Answer
> 3 votes
# Python, ~~93~~ 99

```
from string import *
d=digits+letters
def t(n,b):
 s=''
 while n>0:s=d[n%b]+s;n/=b
 return s or '0'

```

**EDIT**: " or '0'" added for empty string case

# Answer
> 2 votes
# Ruby 1.9 - 80 74 68

```
t=->n,b{d=*?0..?9,*?a..?z,*?A..?Z;s='';(s=d[n%b]+s;n/=b)while n>0;s}

```

With '0' for empty string, 95 89 82 characters:

```
t=->n,b,s=''{d=*?0..?9,*?a..?z,*?A..?Z;(s=d[n%b]+s;n/=b)while n>0;s.empty?? ?0: s}

```

Ruby 1.9 - unfortunately only works up to base 36:

```
t=->n,b{n.to_s(b)}

```

# Answer
> 2 votes
# Ruby - 72 70 59 chars

```
f=->n,b{(n<b ? "":f[n/b,b])+[*?0..?9,*?a..?z,*?A..?Z][n%b]}

```

## Without recursion, 70 chars

```
f=->n,b{d=*?0..?9,*?a..?z,*?A..?Z;s=d[n%b];s=d[n%b]+s while(n/=b)>0;s}

```

Test

```
irb(main):080:0> f[351837066319, 31]
=> "codegolf"
irb(main):081:0> f[0, 31]
=> "0"

```

# Answer
> 2 votes
# dc, 61 chars

```
[sr[lr~rd0<x]dsxxk[39+]sa[58-]sb[d9<ad78<b48+anz0<p]dspxIP]sf

```

Run as:

```
dc -e'[sr[lr~rd0<x]dsxxk[39+]sa[58-]sb[d9<ad78<b48+anz0<p]dspxIP]sf' -e'351837066319 31 lfx'

```

or:

```
dc -f base.dc -e '351837066319 31 lfx'

```

Explanation: We take the number and base on the stack. `sr` saves the base in register r. The recursive function `[lr~rd0<x]dsxx` decomposes a number `TOS` into its digits in base `register r`. The first digit is always 0, removed from the stack by `k` (set precision, which by default is 0 also, so it's equivalent to a nop). Then, the recursive function `[48+d57<ad122<banz0<p]dspx` outputs each digit in ASCII, with the help of functions a (`[39+]sa`) and b (`[58-]sb`). `IP` outputs a newline. The function is stored in register `f`, and can be invoked by `lfx`.

# Answer
> 2 votes
# Python 2, 64 bytes

```
f=lambda n,b:n and f(n/b,b)+chr(n%b+48+(n%b>9)*39-n%b/36*58)or''

```

Try it online!

# Answer
> 2 votes
# Burlesque, 4 bytes

```
peB!

```

Try it online!

Luckily a built-in in Burlesque

```
pe # Parse and push
B! # Convert base

```

# Answer
> 1 votes
## Haskell, 109 characters

```
m=divMod
d(0,x)b=[f x]
d(r,x)b=f x:d(m r b)b
f=(!!)$['0'..'9']++['a'..'z']++['A'..'Z']
s x b=reverse$d(m x b)b

```

# Answer
> 1 votes
# Bash, 79 chars

```
f(){
dc<<<$2o$1p|perl -pe"y/A-Z/a-z/;s/ \d+/chr$&+($&<10?48:$&<36?87:29)/ge"
}

```

# Answer
> 1 votes
## Befunge - 53 x 2 = 106 characters

Or 53 + 46 = 99 characters if you're willing to route other parts of your program through the bottom left.

```
11p01-\>:11g%\11g/:#v_$>:1+!#v_:45+`!#v_:75*`!#v_   v
       ^            <  ^,    $# +"0"  < +"'"   <-":"<

```

First place the number to be converted on the stack, then the radix and enter this function from the top-left going right. Will output the string for you (since Befunge doesn't support string variables) and leave from the bottom `$` going down. Requires the `(1,1)` cell for radix storage.

E.g. for the example given put `351837066319` into the input and run:

```
&56*1+    11p01-\>:11g%\11g/:#v_$>:1+!#v_:45+`!#v_:75*`!#v_   v
                 ^            <  ^,    $# +"0"  < +"'"   <-":"<
                                       @

```

# Answer
> 1 votes
## Golfscript - 32 chars

```
{base{.9>39*+.74>58*48--}%''+}:f

```

# Answer
> 1 votes
# Jelly, 5 bytes

```
b‘ịØB

```

Try it online!

The case will be reversed (codegolf - CODEGOLF) because of Jelly built-in base characters string.

### How?

```
b‘ịØB - Link, input x & y
b     - Convert x to base y
 ‘    - Increment (because Jelly use based-1 indexing)
  ị   - List (string) indexing
   ØB - "0-9 A-Z a-z"

```

# Answer
> 1 votes
# Go, 76 bytes

```
package m
import."math/big"
func e(n int64)string{return NewInt(n).Text(62)}

```

bonus decode:

```
package m
import."math/big"
func d(s string)int64{o,_:=NewInt(0).SetString(s,62)
return o.Int64()}

```

# Answer
> 1 votes
# Japt, 9 bytes

Follows the example of the Jelly solution in reversing the casing.

```
;sVîEowi%

```

Try it

# Answer
> 1 votes
# Stax, 5 bytes

```
VL(:B

```

Run and debug it

Same size packed, a custom base conversion.

# Answer
> 0 votes
# Perl 5 `-Minteger -ap`, 52 bytes

```
do{$\=(0..9,a..z,A..Z)[$_%$F[1]].$\}while$_/=$F[1]}{

```

Try it online!

# Answer
> 0 votes
# 05AB1E (legacy), ~~8~~ 7 bytes

```
вžLšRsè

```

-1 byte by switching to the legacy version of 05AB1E, where the switch\_case builtin was one byte (it's  in the new version).

Inputs in the order \\$radix,number\\$. Output as a list of characters.

Try it online.

**Old 8 bytes non-legacy 05AB1E answers (same I/O as above):**

**Explanation:**"

```
в        # Convert the second (implicit) input to base-(first implicit input) as list
 žL      # Push string "zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210"
   š     # Switch case: "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210"
    R    # Reverse it: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
     s   # Swap so the list is at the top
      è  # Index each into this string
         # (after which the resulting character-list is output implicitly)

```

```
žh       # Push constant string "0123456789"
    «    # Append
  ži     # Constant string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
         #  "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
     £   # Only keep the first (implicit) input amount of characters from this string
      Åв # Convert the second (implicit) input to this custom base-"0-9a-zA-Z"
         # (which basically converts it to base-length, and indexes it into the string)
         # (after which the resulting character-list is output implicitly)

в        # Convert the second (implicit) input to base-(first implicit input) as list
 žK      # Push string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789"
   9Ý    # Push list [0,1,2,3,4,5,6,7,8,9]
     †   # Filter all those characters to the front:
         #  "012346789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
      s  # Swap so the list is at the top
       è # Index each into this string
         # (after which the resulting character-list is output implicitly)

```

# Answer
> 0 votes
## Pascal, 236 B

This function requires a processor supporting features of Extended Pascal as described by ISO standard 10206, in particular the string capabilities. Note, the golfed version is restricted to 98 digits. Furthermore, a character (here the sign) is *always* prepended.

```
type s=string(99);function f(n,b:integer):s;begin
f:=('- +')[ord(n>0)-ord(n<0)+2];n:=abs(n);repeat
f:=('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')[n mod b+1]+f;n:=n div b
until n=0;n:=length(f);f:=f[n]+f[1..n-1]end

```

Ungolf’d, annotated and reasonably good programming style:

```
    const
        { Number of binary digits required to write `maxInt` out. }
        maxIntBinaryLength = trunc(ln(maxInt) / ln(2)) + 1;
        { Known digits for `positionalNotation` function. }
        digit = '0123456789abcdefghijklmnopqrstuvwxyz' +
                          'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        { Characters for negative sign, no sign, and positive sign. }
        sign = '− +';

    type
        { For sorting purposes starts with `integer…` prefix. }
        integerNonNegative = 0‥maxInt;
        { A string capable of representing any integer plus a sign. }
        integerString = string(maxIntBinaryLength + 1);
        { Acceptable `base` for `positionalNotation` function. }
        radix = 2‥62;

    { Returns −1, 0, or +1 depending on the sign of the argument. }
    function signum(protected n: real): integer;
        begin
            signum ≔ ord(n > 0) − ord(n < 0)
        end;

    { Retrieve positional notation of a given integer in a given base. }
    function positionalNotation(
            protected n: integer;
            protected base: radix
        ): integerString;
        { Separate string to work with, and ensure non‑negative number. }
        function position(magnitude: integerNonNegative): integerString;
            begin
                position ≔ '';
                { This is just your run‑of‑the‑mill Horner’s method. }
                repeat
                begin
                    { Prepend a digit. Note, string indices are 1‑based. }
                    position  ≔ digit[magnitude mod base + 1] + position;
                    magnitude ≔ magnitude div base
                end
                until magnitude = 0
            end;
        begin
            { The algorithm is prepending digits, but the sign must be first. }
            positionalNotation ≔ sign[signum(n) + 2] + position(abs(n))
        end

```

Signum function PPCG challenge │ RosettaCodeFreePascal Wiki

---
Tags: code-golf
---


title: Rank poker High Card hands

text:
# Question
Title: Rank poker High Card hands
In the poker game there are 1277 unique 'High Card' ranks. It's 1287 (13 over 5) if we include all straights.

The challenge is to write a function which returns an integer value corresponding to the rank of each 'High Card' poker combination including all straights. Possible cards are(in ascending order): '23456789TJQKA'

```
23456 -> 1
23457 -> 2
23467 -> 3
23567 -> 4
....
8JQKA -> 1285
9JQKA -> 1286
TJQKA -> 1287

```

# Answer
> 2 votes
# JavaScript (Node.js), 71 bytes

```
x=>(y=g=(a,i=13)=>a[4]?y|=a==x:i&&g('23456789TJQKA'[--i]+a,i)+g(a,i))``

```

Try it online!

```
x=>(             // Input
  y=             // Init y to not-a-number (behaves as 0)
  g=             // and define a function to recurse
  (a,i=13)=>     // a is current string,
                 // i is possible chosen characters left
    a[4]?        // current string length 5
      y|=a==x    // set y to 1 if a==x, otherwise remain
                 // then returns y
                 // This counts how many times called
                 // after a==x
    :            // otherwise(length is not 5)
      i&&        // if no characters left, return 0
      g('23456789TJQKA'[--i]
          +a,i)+ // First count if the next char is chosen
      g(a,i)     // then if it isn't chosen
                 // Therefore, if all characters after X
                 // both appear or both don't appear in
                 // string P and Q, and P includes X
                 // while Q doesn't, then P is executed
                 // earlier than Q.
)``              // Calls g with [''], which behaves
                 // same as empty string.

```

# Answer
> 3 votes
# Jelly, 20 bytes

```
9RḊṾ€;“TJQKA”Ṛœc5ṚiṚ

```

Try It Online!

### Explanation

```
9RḊṾ€;“TJQKA”Ṛœc5ṚiṚ    Main Link
9R                      [1, ..., 9]
  Ḋ                     Dequeue: [2, ..., 9]
   Ṿ€                   Un-Eval Each: "23456789"
     ;“TJQKA”           Append: "23456789TJQKA"
             Ṛ          Reverse: "AKQJT98765432"
              œc5       Combinations of length 5
                 Ṛ      Reverse
                  iṚ    Find the index of the reversed input

```

This isn't quite lexicographical order, it's sort of the opposite, so we must reverse the generation string, the combination list itself, and the input to account for this.

# Answer
> 2 votes
# JavaScript (ES6), 105 bytes

Expects an array of characters.

```
a=>(g=a=>a.some(v=>(i++&&x+1)<(x=v),i=0)?1+g(a.map(v=>i?x-i--:v)):1)(a.map(c=>"23456789TJQKA".search(c)))

```

Try it online!

---
Tags: code-golf, sequence, integer
---