title: Largest power of 2 that divides \$n\$

text:
# Question
Title: Largest power of 2 that divides \$n\$
Related, related

# Introduction

The ruler sequence is the sequence of the largest possible numbers \\$a\_n\\$ such that \\$2^{a\_n}\mid n\\$. It is so-called because its pin plot looks similar to a ruler's markings:

However, with a slight modification, we can also get a similar sequence. This sequence is \\$\\{a\_1,a\_2,a\_3,…\\}\\$ where \\$a\_n\\$ is the largest **power of 2** such that \\$a\_n\mid n\\$ (relevant OEIS).

The first 100 terms of this sequence are:

```
1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 64, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32, 1, 2, 1, 4

```

# Challenge

Your challenge is to do one of these three things:

* Take a positive integer \\$n\\$ as input and return the \\$n\\$th term of this sequence.
* Take a positive integer \\$n\\$ as input and return the first \\$n\\$ terms of this sequence.
* Output the sequence infinitely.

# Test Cases

```
12 -> 4
64 -> 64
93 -> 1
8 -> 8
0 -> (undefined behavior)

```

# Rules

* You may output the sequence in any convenient format - e.g. as a list or some other iterable or separated by any non-digit separator, as long as it is constant between all terms.
* You may output the term(s) in any convenient format - e.g. as an integer, as an integer string, as a float with the decimal part consisting of only zeros, ditto but as a string, or as a Boolean (`True`) if and only if the term is `1`.
* You may choose to use either zero- or one-indexing.
* Standard loopholes are forbidden.
* Trailing whitespace is allowed.
* If possible, please link to an online interpreter (e.g. TIO) to run your program on.
* Please explain your answer. This is not necessary, but it makes it easier for others to understand.
* This is , so shortest code in bytes wins!

# Answer
> 5 votes
# Jelly, 2 bytes

```
N&

```

Try it online!

Takes \\$n\\$ as input, outputs the \\$n\\$th term

## How it works

Uses dinglelooper’s observation

# Answer
> 19 votes
# Python 2, 13 bytes

Takes a positive integer \\$ n \\$ as input and returns the \\$ n \\$th term of the sequence.

```
lambda n:n&-n

```

Try it online!

The largest power of \\$ 2 \\$ that divides \\$ n \\$ is also the lowest set bit. The bitwise magic is a bit difficult to explain, but it uses the fact that `~n + 1` in its binary representation produces the same lowest set bit as `n`.

### Python 2, 26 bytes

Outputs the sequence infinitely.

```
n=1
while 1:print-n&n;n+=1

```

Try it online!

### Python 2, 33 bytes

Takes a positive integer \\$ n \\$ as input and returns the first \\$ n \\$ terms of the sequence.

```
f=lambda n:n*[0]and f(n-1)+[n&-n]

```

Try it online!

# Answer
> 12 votes
# Regex (ECMAScript), 13 bytes

```
(x+?)(\1\1)*$

```

Try it online!

Works by finding the smallest positive natural number that divides the input yielding an odd quotient. As such, this algorithm is generally applicable to any power of \\$p\\$, where \\$p\\$ is prime: find the smallest number that divides the input yielding a quotient that is not divisible by \\$p\\$.

Takes its input in unary, as a sequence of `x` characters in which the length represents the number. The output is returned in capture group 1.

```
          # No anchor needed, since every input N>=1 returns an output
(x+?)     # \1 = the smallest number >= 1 for which:
(\1\1)*$  # \1 divides N and N / \1 is odd

```

Below is a demonstration showing how the algorithm above generalizes to other prime powers:

Largest power of \\$3\\$ that divides \\$n\\$ (17 bytes): `(x+?)\1?(\1{3})*$` \- Try it online!

Largest power of \\$5\\$ that divides \\$n\\$ (21 bytes): `(x+?)\1{0,3}(\1{5})*$` \- Try it online!

Largest power of \\$17\\$ that divides \\$n\\$ (23 bytes): `(x+?)\1{0,15}(\1{17})*$` \- Try it online!

# Answer
> 8 votes
# Haskell, 19 bytes

```
l=1:do x<-l;[2*x,1]

```

Try it online!

Generates an infinite list. This list is defined recursively using the property that the list is unchanged if we double each value and intersperse 1's at every other position including at the start.

So, we start the list with a `1`, then iterate through the list itself, each time producing the doubled number followed by a `1`. Haskell's laziness allows this kind of self-reference.

```
1   <- initial value
2 \ 1 doubled
1 /
4 \ 2 doubled
1 /
2 \ 1 doubled
1 /
8 \ 4 doubled
1 /
2 \ 1 doubled
1 /
...

```

---

# Haskell, 10 bytes

```
gcd=<<(2^)

```

Try it online!

Outputs the n'th term. Equivalent to `f n=gcd n(2^n)`. We take the greatest common divisor of `n` and a large power of 2.

# Answer
> 7 votes
# 05AB1E, 5 bytes

```
LoÖOo

```

Try it online!

Takes \\$n\\$ as input, outputs the \\$n\\$th term

## How it works

```
LoÖOo - Full program. Input n
L     - Range from 1 to n
 o    - Raise 2 to the power of each
  Ö   - Yield 1 if divisible by n, for each
   O  - Sum, counting the 1s
    o - Raise 2 to the power

```

---

# 05AB1E, 2 bytes

```
(&

```

Try it online!

Boring bitwise solution. Calculates the bitwise AND of \\$n\\$ and \\$-n\\$

# Answer
> 5 votes
# JavaScript (V8), 18 bytes

```
f=n=>n&1||2*f(n/2)

```

Try it online!

# Answer
> 5 votes
# C (gcc) x86, 14 bytes

Takes a positive integer \\$n\\$ as input and returns the \\$n\\$th term of the sequence.

```
f(n){n&=-*&n;}

```

Try it online!

```
f(n){*&n&=-n;}

```

Try it online!

Same bitwise formula as used ChartZ Belatedly, dingledooper, and many more. Thanks to Noodle9 for the nice idea of showing ✓ or ✕ in the TIO code depending on correctness; I haven't done that before, but might use it some more in the future.

Uses the very common code golf hack of avoiding the non-golfy `return` keyword (by taking advantage of the fact that results to most calculations get stored in the accumulator, the same register that is used for return values), but without resorting to use of global variables or fake function parameters. This is done by taking the address of `n` and then dereferencing that address.

This of course requires the default optimization level `-O0`. Using `-O1` will break gcc `return` avoidance hacks (and in clang, they don't even work at `-O0`).

In 32-bit x86, this compiles to the following (`[ebp+0x8]` is the `n` parameter):

```
 mov    eax,DWORD PTR [ebp+0x8]
 neg    eax
 mov    edx,eax
 mov    eax,DWORD PTR [ebp+0x8]
 and    eax,edx
 mov    DWORD PTR [ebp+0x8],eax

```

Whereas `f(n){n&=-n;}` doesn't work because it compiles to the following, which acts like `f(n){return-n;}`:

```
 mov    eax,DWORD PTR [ebp+0x8]
 neg    eax
 and    DWORD PTR [ebp+0x8],eax

```

An essentially equivalent result occurs in x86-64 and MSP430.

# C (gcc) \- many other platforms, 12 bytes

```
f(n){n&=-n;}

```

On many architectures other than x86, this actually works:

ARM64 gcc 10.2
ARM gcc 10.2.1
KVX gcc 7.5 (ACB 4.1.0-cd1)
MIPS64 gcc 5.4
MIPS gcc 5.4
PowerPC64 AT13.0 (gcc9)
RISC-V rv64gc gcc 10.2.0
AVR gcc 5.4.0

This is case in point for why I hate the gcc `return` avoidance hack so much. It's not merely reliant on `-O0`, and not only uses undefined behavior in general, but it's not even portable within different architecture targets of `gcc` itself.

Here it is failing to work as desired on x86 and MSP430, contrasted with the `*&` forcing it to work:

x86-64 gcc 10.2
x86-32 gcc 10.2
x86-32 gcc 5.4
MSP430 gcc 6.2.1

There is no guarantee that the same undefined behaviors will still behave the same way in future versions of gcc (and/or the toolset) even on the same architecture.

This is why I prefer to post "C (clang)" or "C (gcc `-O1`)" answers instead of "C (gcc)". If the fragile undefined behavior hacks work, you have to use them in "C (gcc)" answers to stay competitive with other "C (gcc)" answers.

In any case, people posting answers that use this hack should probably call the language "C (gcc) x86" instead of "C (gcc)".

# C (gcc), 37 bytes

Outputs the sequence infinitely.

```
main(n){for(;;)printf("%d   ",-n&n++);}

```

Try it online!

Saves 1 byte by using tab (which can be used literally) instead of newline (which would require `\n`). Takes another shortcut by using the first parameter of `main()`, the command line argument count, which is 1 when there are no command line arguments (because the pathname of the executable is treated as the first argument, at index 0).

# C (gcc), 52 bytes

Takes a positive integer \\$n\\$ as input and outputs the first \\$n\\$ terms of the sequence.

```
main(n){for(scanf("%d",&n);n;)printf("%d    ",-n&n--);}

```

Try it online!

Abuses a loophole by printing the first \\$n\\$ terms in descending instead of ascending order. Without this, it would be **~~57~~ 56 bytes**:

```
main(i,n){for(scanf("%d",&n);n--;)printf("%d    ",-i&i++);}

```

Try it online!

# C (gcc), 53 bytes

Takes a positive integer \\$n\\$ as input and returns the first \\$n\\$ terms of the sequence.

```
f(n){int*m=malloc(n*4);for(;n;)m[n]=-n&n--;n=(int)m;}

```

Try it online!

`4` is `sizeof(int)`.

`m[n]=-n&n--;` works because by the time `m[n]` evaluates, `n` has already been decremented; it's equivalent to `m[n-1]=-n&n;--n;`.

The array returned is allocated by this function, and must be `free()`ed after use.

# Answer
> 4 votes
# , 6 4 bytes

```
AND-

```

Try it online!

-2 thanks to FrownyFrog

Just because expressing dingledooper's idea in J is nice....

* `...-` The whole thing is a J hook, so that the verb `...` will receive the input and its negative as the left and right argument.
* `AND` Elementwise "and" on the bits.

# Answer
> 4 votes
# Octave / MATLAB, ~~28~~ 23 bytes

*5 bytes off thanks to @Giuseppe!*

```
@(n)2^sum(factor(n)==2)

```

Try it online!

### Explanation

```
@(n)                      % Define anonymous function of n
          factor(n)       % Vector of prime factors of n, possibly repeated
                   ==2    % Compare each element with 2. Gives 1 (true) or 0 (false)
      sum(            )   % Sum
    2^                    % 2 raised to that

```

# Answer
> 3 votes
# , ~~34~~ ~~33~~ 32 bytes

*Edit: -1 byte thanks to Giuseppe*

```
function(n,t=2^(n:0))t[!n%%t][1]

```

Try it online!

Constructs a series `t` of powers of 2 in reverse (`t=2^(n:0)`), then gets the first element (`[1]`) for which n MOD t is zero (`[!n%%t]`).

This works *in principle* for any `n`, but is limited by floating-point accuracy and - more obviously - calculation time and memory. A faster and less memory-hungry (but 7 byte longer) version using the same approach would be: `function(n,t=2^(0:log2(n)))max(t[!n%%t])` (try it).

---

# , 34 bytes

```
f=function(n)`if`(n%%2,1,2*f(n/2))

```

Try it online!

An alternative recursive approach (ported from user81655's answer) is 1 byte longer, but runs significantly faster and so can actually be tested for very large numbers.

# Answer
> 3 votes
# PowerShell, 19 bytes

```
param($n)$n-band-$n

```

Try it online!

It does:

* Take a positive integer \\$n\\$ as input and return the \\$n\\$th term of this sequence.

Thanks to @xnor

# Answer
> 3 votes
# Scala, 8 bytes

```
n=>n& -n

```

Try it online!

dingledooper's idea works also in Scala

# Answer
> 3 votes
# Wolfram Language (Mathematica), 11 bytes

```
GCD[2^#,#]&

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~8~~ 6 bytes

```
ÝoʒÖ}θ

```

Try it online!

Turns out I'm way too used to Vyxal. -2 thanks to Makonede

## Explained

```
ÝoʒÖ}θ
Ýo      # 2 ** range(0, input) // vectorised
  ʒÖ}   # filter(lambda x: x % input == 0, ^)
     θ  # ^[-1]

```

# Answer
> 2 votes
# Vyxal, 2 bytes

```
N⍲

```

Try it Online!

Just a port of the bitwise stuff.

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

```
n=>n&-n

```

Try it online!

dingledooper's solution (for Python) adapted to JavaScript.

# Answer
> 2 votes
# Java (JDK), 7 bytes

```
n->n&-n

```

Try it online!

dingledooper's solution (for Python) adapted to Java

# Answer
> 2 votes
# , 24 bytes

```
function(n)bitwAnd(n,-n)

```

Try it online!

While it's good to have a variety of answers using different techniques, the actual shortest in each language should be represented too. As is the case in most languages, I think the bitwise hack is the shortest here.

# Answer
> 2 votes
# Groovy, 8 bytes

```
{it&-it}

```

Try it online!

dingledooper's Python solution, translated to Groovy

# Answer
> 2 votes
# C (gcc), 15 bytes

```
a;f(n){a=n&-n;}

```

Try it online!

Inputs a positive integer \\$n\\$ and returns \\$2^a\\$ which is the largest power of \\$2\\$ such that \\$2^a\mid n\\$.

# Answer
> 2 votes
# Julia, 18 bytes (recursive approach)

```
!n=n%2>0||2*!(n/2)

```

Try it online!

# Julia, 7 bytes (bitwise approach)

```
n->n&-n

```

Try it online!

# Answer
> 2 votes
# Perl 5, 15 bytes

```
sub($n){$n&-$n}

```

Try it online!

dingledooper's Python solution, translated to Perl 5

# Answer
> 2 votes
# Japt, 3 bytes

`U` is the first input, same bitwise approach as many other answers already covered.

```
&-U

```

Try it out here.

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), 72 bytes

```
	N =INPUT
	X =1
I	J =N / X
	X =X * 2	EQ(REMDR(J,2))	:S(I)
	OUTPUT =X
END

```

Try it online!

```
	N =INPUT				;* read input
	X =1					;* set X =1
I	J =N / X				;* set J to N / X
	X =X * 2	EQ(REMDR(J,2))	:S(I)	;* If J is divisible by 2, double X and goto I, else
	OUTPUT =X				;* print X and exit
END

```

# Answer
> 2 votes
# Factor, ~~56~~ ~~50~~ 46 bytes

* Saved 6 bytes thanks to @Bubbler!
* Saved 4 bytes thanks to @chunes!

```
[ 2 over [0,b] n^v [ 2 * mod 0 > ] with find ]

```

Try it online!

# Factor, 53 bytes

```
[ 0.5 [ [ 2 / ] [ 2 * ] bi* over dup floor = ] loop ]

```

Try it online!

# Answer
> 2 votes
# Factor, 14 bytes

```
[ dup 2^ gcd ]

```

Try it online!

J42161217's and xnor's approach: GCD with a large power of 2.

# Factor, 18 bytes

```
[ dup neg bitand ]

```

Try it online!

Bitwise approach already done by many different answers.

# Factor, 18 bytes

```
[ factor-2s . 2^ ]

```

Try it online!

There's a built-in that is supposed to do most of the job: `factor-2s`, which takes a positive integer `n` and returns `[ exponent-of-2 odd-part ]` on the stack. Unfortunately the power of 2 is the secondary return value (so you need to discard the top with `.`) and it is the exponent (not the power of 2 itself) so `2^` is needed.

# Answer
> 2 votes
# Excel, ~~29~~ 24 bytes

*-5 bytes thanks to @TaylorScott*

A port of Dingledooper's answer to Excel.

```
=BITAND(2^47+A1,2^47-A1)

```

## Original much worse answers, 29 bytes

```
[A2]=2^47+A1*{1;-1}
[A4]=BITAND(A2,A3)

```

Had to use 2 cells because `BITAND` requires 2 arguments. The formula in A2 spills to A3. Works up to 2^47 - 1. Can save a byte changing 2^47 to 8^9. This lowers the range to 2^27-1.

## Excel (one cell), 35 bytes

```
=2^SUM(1*(MOD(A1,2^(ROW(1:47)))=0))

```

This is what I came up with on my own. Works up to 2^41.

Try them online

# Answer
> 1 votes
# Scala, 43 bytes

```
n=>Stream.iterate(1)(_*2).find(n%_>0).get/2

```

Try it in Scastie!

# Answer
> 1 votes
# 05AB1E, 2 bytes

```
o¿

```

Try it online!

```
o¿  # full program
 ¿  # greatest common divisor of...
    # implicit input...
 ¿  # and...
o   # 2 to the power of...
    # implicit input
    # implicit output

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 16 bytes

Nth Term

```
{2*(⊥⍨~)2⊥⍣¯1⊢⍵}
 2* ⍝ exponentiation
   ⊥⍨~ ⍝ number of trailing zeros
      2⊥⍣¯1⊢ ⍝ bit vector conversion
            ⍵ ⍝ argument

```

Try it online!

---

# APL (Dyalog Unicode), 21 bytes

First N Terms

```
{2*(⊥⍨~)∘(2⊥⍣¯1⊢)¨⍳⍵}
 2* ⍝ exponentiation
   ⊥⍨~ ⍝ number of trailing zeros
      ∘ ⍝ curry
       2⊥⍣¯1⊢ ⍝ bit vector conversion
             ¨ ⍝ each
              ⍳⍵ ⍝ range of 1–n

```

Try it online!

# Answer
> 1 votes
# Pyt, 3 bytes

```
Đ~∧

```

Try it online!

Port of dingledooper's Python solution

# Answer
> 1 votes
# Thunno, \\$4 \log\_{256}(96) \approx \\$ 3.29 bytes

```
DnA&

```

Attempt This Online! or verify the first 100 terms

Uses dingledooper's observation.

```
DnA&  # Implicit input
Dn    # Duplicate and negate top copy
  A&  # Bitwise AND of the two numbers
      # Implicit output

```

# Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
ZhAJ2@

```

Attempt This Online! or verify the first 100 terms

Inspired by ovs's comment.

```
ZhAJ2@  # Implicit input
Zh      # Prime factor exponents of the input
  AJ    # First element (i.e. the exponent of 2)
    2@  # 2 ** that
        # Implicit output

```

---
Tags: code-golf, math, number
---


title: Input ∩ Source Code

text:
# Question
Title: Input ∩ Source Code
## Intro

The challenge is to create a program/function that prints the intersection of its own source code and a given string input. This is code golf and to be more precise:

* Let `I` be the input set
    + `{"a","b","c"}`
* Let `S` be the source code set
    + `{"b","f"}`
* Then the intersection is what they share
    + `I ∩ S = {"b"}`

## Input

Input is flexible. It should be able to handle the character encoding used for the source code.

## Output

Output is flexible. It should be the set of characters that the input and source code share. Also, sets are unordered collections of distinct objects. In summary:

* Output is flexible:
    + Could be any data structure (string or otherwise)
    + Could unordered
    + Could have a trailing `\n`
    + Should be distinct

## Restriction

Similar to challenges, the program/function may not read its own source code and 0-byte solutions are not allowed.

## Examples

* **#1**

```
functor x(I){ return I ∩ self; }

Inputs                                Outputs
------                                -------
enter preformatted text here      ->  {"e","n","t","r","f","o","x"}

["Albrt"," Einstin"]              ->  {"l","r","t","n","s"}

```
* **#2**

```
(_)->_&"(_)->&\"\\"

Inputs                                Outputs
------                                -------
"Security at the expense of       ->  "
usability comes at the expense
of security."

(0____0)                          ->  (_)

```
* **#3**

```
ಠa益длф

Inputs                                Outputs
------                                -------
Far out in the uncharted backwaters ->"a"
of the unfashionable end of the
Western Spiral arm of the Galaxy lies
a small unregarded yellow sun.
Orbiting this at a distance of roughly
ninety-eight million miles is an
utterly insignificant little blue-green
planet whose ape-descended life forms
are so amazingly primitive that they
still think digital watches are a pretty
neat idea.

(ノಠ益ಠ)ノ彡┻━┻                      ->"ಠ益"

```

## Test Cases

```
Albert Einstein

\__( O__O)_/

!@#$%^&*()_+{}|:"<>?

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”

┬──┬ ノ( ゜-゜ノ)

Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.

```

**Update**

* \[16-08-10\]: sets are unordered collections of distinct objects
* \[16-08-10\]: trailing newline is acceptable

# Answer
# Jelly, ~~10~~ 6 bytes

```
“Ṿf”Ṿf

```

Try it online!

### How it works

```
“Ṿf”Ṿf  Main link. Argument: s (string)

“Ṿf”    Set the return value to 'Ṿf'.
    Ṿ   Uneval; yield '“Ṿf”'.
     f  Filter; remove the characters from '“Ṿf”' that do not appear in s.

```
> 24 votes

# Answer
## Python 3, 44 bytes

Thanks Karl for saving me one byte :-) Thanks Dada for saving me two bytes!

I think this works, but it's my first quine challenge so I'm not 100% sure. :\

```
print(set("printseu()&'"+'+"')&set(input()))

```

Lambda version with 43 bytes: `lambda a:set(" lambdaset()&'"+':+"')&set(a)`
> 14 votes

# Answer
# Dyalog APL, 8 bytes

```
'∩''⊢'∩⊢

```

is returns those characters from the left argument that are present in the right argument (if the **left** argument has no duplicates – as in this case – then the result also has no duplicates

is the argument

Then the string just has those two plus the quote character (doubled, as it is in a string).

TryAPL online!
> 11 votes

# Answer
# GolfScript, 6 bytes

```
"`&"`&

```

Try it online!

### How it works

```
        # (implicit) Push the input on the stack.
"`&"    # Push the string '`&' on the stack.
   `    # Inspect; turn the string into '"`&"'.
     &  # Perform set intersection.

```
> 10 votes

# Answer
# Perl 6, 56, 55 bytes

**"*French*" / Unicode version** (55 bytes)

```
say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb:

```

**"*Texas*" / ASCII versions** (56 bytes)

```
say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl

```

```
say perl q.sayq(&) $*IN\\\.comb:perl..comb (&)$*IN.comb:

```

# Non-golfed:

```
my \Source = 'my \\Source = \'say ( $*IN.comb.Set ∩ Source.comb.Set ).perl\'';
say ( $*IN.comb.Set ∩ Source.comb.Set ).perl

```

# Examples:

```
$ echo -n 'say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb:' > test-unicode.p6

$ echo -n 'say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl' > test-ascii.p6

$ perl6 test-ascii.p6 <<< 'abcdefghijklmnopqrstuvwxyz'
set("p","a","l","r","c","q","b","s","e","m","y","o")

$ perl6 test-unicode.p6 < test-unicode.p6
set("\\","I","p"," ","a","c","l","r","q","b","∩","*","s","m","e",".","y",":","o","N","\$")

$ perl6 test-ascii.p6 < test-ascii.p6
set("p","\\","I"," ","a","l","r","c","q","b",")","*","s","e","m","\&",".","(","y","o","N","\$")

$ perl6 test-ascii.p6 < test-unicode.p6
set("p","\\","I"," ","a","l","r","c","q","b","*","s","e","m",".","y","o","N","\$")

$ perl6 test-unicode.p6 <<< 'Albert Einstein'
set(" ","l","r","b","s","e")

$ perl6 test-unicode.p6 <<< '\__( O__O)_/'
set("\\"," ")

$ perl6 test-ascii.p6 <<< '!@#$%^&*()_+{}|:"<>?'
set(")","*","\&","(","\$")

$ perl6 test-unicode.p6 <<< "1234567890-=[]\\;',./"
set("\\",".")

$ perl6 test-unicode.p6 <<< '(ノಠ益ಠ)ノ彡┻━┻'
set()

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”
set("o")

$ perl6 test-unicode.p6 <<< '┬──┬ ノ( ゜-゜ノ)'
set(" ")

$ perl6 test-ascii.p6 <<< 'Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.'
set("p"," ","a","l","r","c","b","s","e","m",".","y","o")

```
> 8 votes

# Answer
# Python 2, ~~56~~ ~~46~~ 39 Bytes

*-1 Byte thanks to @Jeremy*

```
lambda a:set(':&()smelt\ bad\'')&set(a)

```

anonymous lambda function, takes a string, returns a set

old version:

```
lambda x,w=set('newmatrixbuspdl_:-)(=,\ \''):w-(w-set(x))

```
> 8 votes

# Answer
# MATL, 8 bytes

```
'X&'''X&

```

**Try it online!**

Input is a string enclosed in single quotes. If the string contains a single-quote symbol, it should be duplicated to escape it.

### Explanation

```
'X&'''   % Push string with the three characters used by the program. The single-quote
         % symbol needs to be escaped by duplicating it
X&       % Take input implicitly. Set intersection. Display implicitly

```
> 7 votes

# Answer
## Actually, 6 bytes

```
`∩è`è∩

```

Try it online!

Explanation:

```
`∩è`è∩
`∩è`    push the function `∩è` (which contains every character in the source code except '`')
    è   repr (same as Python repr - leaves "`∩è`", which contains every character in the source code)
      ∩ set intersection with input

```
> 7 votes

# Answer
# C, 142 bytes

```
main(i){char*p,a[]="remain([*]){fought?>:01;,\\\"=capsv+-l}";for(;(i=getchar())>=0;p?putchar(i),memmove(p,p+1,a+strlen(a)-p):0)p=strchr(a,i);}

```

Try it on ideone.
> 5 votes

# Answer
# Haskell (30 bytes)

This is such a boring solution... But I couldn't do better. :(

```
filter(`elem`"f(term)\"i`l\\")

```
> 5 votes

# Answer
# Brachylog, 23 bytes

```
:{e.~e":{}e~\"fd\."}fd.

```

Try it online!

### Explanation

```
:{                 }f      Find all chars that verify the predicate below
                     d.    Remove duplicates and output

  e.                       Take a char from the input ; this is our output…
    ~e":{}e~\"fd\."        … if that char is in the string :{}e~"fd. (the first \ is here
                               to escape the ")

```
> 5 votes

# Answer
# 05AB1E, 11 bytes

Code:

```
"'ÃJÙ"'"JÃÙ

```

Uses the **CP-1252** encoding. Try it online!.
> 4 votes

# Answer
# Pyth, ~~9~~ 8 bytes

**1 byte thanks to Sp3000**

```
@Q"\Q@\"

```

Try it online!

```
@Q"\Q@\"
@Q"\Q@\""   implicit string ending

@Q           intersect the input with
  "\Q@\""   the string containing '\', 'Q', '@', '"'.

```
> 4 votes

# Answer
# Bash, ~~45 50 41 39 37 34~~ 29 bytes

-9 bytes thanks to Geoff Reedy
-4 bytes thanks to Dennis
-5 bytes thanks to Nahuel Fouilleul

```
grep -o '[] [|\'\'grepouniq-]

```

Try it online!
> 4 votes

# Answer
# CJam, 8 bytes

```
"`q&"`q&

```

Try it here.

Explanation:

```
"`q&"    e# Push that string to the stack
     `   e# Stringify, pops the string and pushes "\"`r&\"" to the stack
      q  e# Pushes the input to the stack
       & e# Union, pops two elements and pushes a list of every element that is contained in both.

```
> 4 votes

# Answer
# Retina, ~~21~~ 20 bytes

Removes characters not in the source code, then removes duplicate characters.

```
[^Ds.n\n[-a_-]

Ds`.

```

**Try it online**
> 4 votes

# Answer
# C#, 36 bytes

```
s=>s.Intersect("s=>.Interc(\"\\);");

```

Intended cast is `Func<string, IEnumerable<char>>` (`string` input, `IEnumerable<char>` output).
> 4 votes

# Answer
# Mathematica, 35 bytes

```
Characters@"\"#&@C\acehrst⋂"⋂#&

```

Anonymous function. Ignore any generated messages. Takes a list of characters as input and returns a list of characters as output. The Unicode character is U+22C2 for `\[Intersection]`.
> 4 votes

# Answer
# Vim, ~~78 68 78 79~~ 61 keystrokes

Completely changed my approach:

```
oo/\$kjxd<esc>/o<cr>xj$/\/<cr>xj$/\\<cr>xj$/$<cr>xj$/k<cr>xj$/x<cr>xj$/j<cr>xj$/d<cr>xkdd

```

How it works:

First, it makes a line with all the program characters, then, it finds the first instance of each of the program characters, which is either in the input, if the input and output intersect, or the output if they don't, deletes it, moves to the last character of the file (so it wraps around) and does that for each unique character in source, except d, where instead of moving to the end of the file, it finishes up by deleting the input
> 4 votes

# Answer
## PowerShell v4+, ~~122~~ 104 bytes

```
([char[]]($args[0]+'acegfhmnoprstu012|][()"?+_,.$-{0}{1}{2}'-f("'","}","{"))|group|?{$_.count-gt1}).name

```

Ugh. Quines or quine-like code in PowerShell sucks, because the string replacement formatting is so clunky.

The string `ace...{2}` in the middle is every character that's present in the rest of the code. The `{0}{1}{2}` is used in conjunction with the `-f`ormat operator to pull the `'{}` characters into the string.

That's combined as a char-array with the input `$args`, then fed into the pipeline. The first stop is `Group-Object` which (essentially) creates a hashtable of the input objects and how many times they occur in the input. That's piped to `|?{...}` the `Where-Object` to only select those items that have a `.count` greater than `1`. We encapsulate that in parens, and pluck out the `.Name` portion of the hashtable (which is where the v4+ requirement comes into play, otherwise we'd need an additional `|Select Name` stage to the pipeline).

Those elements are left on the pipeline (as an array), and printing is implicit.
> 3 votes

# Answer
## JavaScript (ES6), ~~59~~ 57 bytes

```
f=
t=>[..."\"().=>O[\\]defilnrtx~"].filter(e=>~t.indexOf(e))
;
```

```
<input placeholder=Input oninput=o.value=f(this.value).join``><input placeholder=Output id=o>
```

Returns an array of characters present in both the original string/character array and the source code. Edit: Saved 2 bytes thanks to @user81655.
> 3 votes

# Answer
## Python 2, 44 bytes

```
x='c=set;print c(`x`)&c(raw_input())';exec x

```

Just for fun, here's a quine-like full program submission. Outputs the string representation of a Python 2 set.
> 3 votes

# Answer
## sed, 47 characters

```
:s;st[^])(*\1.s2t:[;^]tt;st\(.\)\(.*\1\)t\2t;ts

```

I'm a little disappointed at how long this came out to be, especially the bit to remove repeated characters.
> 3 votes

# Answer
# Matlab, 37 bytes

Quite simple:

Uses the builtin `intersect` to find the intersection. The source code is hard coded. Input must be given inside quotation marks `''`

```
intersect(input(''),'''intersc(pu),')

```
> 3 votes

# Answer
# JavaScript (Chrome 58 on OS X 10), ~~12654~~ ~~12426~~ 11992 Bytes

~~https://paste.ubuntu.com/25593218/~~

~~https://paste.ubuntu.com/25595798/~~

https://paste.ubuntu.com/25595831/

The original code:

```
var t=prompt();"!+()[]".split("").forEach(function(f){if(t.includes(f))alert(f)})

```

This was then converted into a programming style called jsfk which only uses these six characters:

```
(+)[!]

```

using an online compiler.
> 3 votes

# Answer
# q (38 bytes)

Reads from `stdin`

```
"readint0\\\" "inter read0 0

```

edit: was missing backslash
> 2 votes

# Answer
# R, 129 bytes

```
f=function(s){b=strsplit("f=unctio(s){arpl;,[1]b\\\"qemh0T}",c())[[1]];cat(b[unique(pmatch(strsplit(s,c())[[1]],b,0,T))],sep="")}

```

If I ungolf it, it needs to have weird things changed like a newline in the string for `b`. Anyhow, its super simple -- builds a vector with all characters in the function in it. Then it pulls the input into a vector, and checks membership.
> 2 votes

# Answer
# Ruby, 34 + `n` flag = 35 bytes

Doesn't exactly work with multi-lined input, since `-n` causes the program to process STDIN line-by-line. There aren't newlines in this code, but trying to input something like that will output multiple arrays instead of one. If that is not good according to spec, please inform me and I will fix.

```
p $_.chars&"\\\"p $_.chars&".chars

```
> 2 votes

# Answer
## Java 8 lambda, ~~152~~ ~~142~~ 140 characters

Quite short:

```
s->s.chars().mapToObj(i->(char)i).filter(c->"COSTab\"\\cefh(i)j+l-mn.oprstuv>".contains(""+c)).collect(java.util.stream.Collectors.toSet())

```

Or ungolfed over here:

```
public class Q89400 {

    static Set<Character> inAndQuine(String in) {
        return in.chars()
                .mapToObj(i->(char)i)
                .filter(c->"COSTab\"\\cefh(i)j+l-mn.oprstuv>".contains(""+c))
                .collect(java.util.stream.Collectors.toSet());

    }
}

```

Of course the ungolfed solution is wrong, as it doesn't match the curly brackets and some more characters, it's just their for the sake of completeness.

The function takes input as a `String` and returns a `java.util.Set<Character>` containing the characters which are present in both input and source.

**Updates**

It turned out that the solution wasn't working. I thought `String#contains` tests for a regex match but it is just a literal matching. I added some escaping to quote the characters like `.` but this wasn't necessary but ruined everything instead. Now without this escaping we save some characters and now it actually works :)

Thanks to @NonlinearFruit for reminding me of using one-character variables.
> 2 votes

# Answer
## ListSharp, 222 bytes

```
STRG S=READ[<here>+"\\S.txt"]
ROWS T=ROWSPLIT S BY [""]
ROWS R=ROWSPLIT "STRG =EAD[<her>+\".tx]OWPLIBYCFMHVNc#isn()oay\r\n" BY [""]
ROWS R=SELECT FROM T WHERE[EVERY STRG IS ANY STRG IN R]
SHOW=<c#R.Distinct().ToArray()c#>

```

***ridiculous but im entertained***
> 2 votes

# Answer
# SQF, ~~71~~ ~~69~~ 64 bytes

Using the file-as-a-function format:

```
i="-_h ;""=()sSplitrng"splitString"";i-(i-(_this splitString""))

```

Call as `"STRING" call NAME_OF_COMPILED_FUNCTION`
> 2 votes

# Answer
# Pyth, ~~6~~ 8 Bytes

```
{@"{@\"\

```

Expects input as a string.

Try it online!

Explanation:

```
 @     Q    Intersect implied input with:
  "{@\"\     The string containing {@"\
{          and then remove duplicates.

```
> 2 votes

# Answer
# MATLAB, 32 bytes

```
@(t)intersect(t,'@(t)inersc,''')

```

Essentially the same as Stewie Griffin's approach (the `intersect` built-in is hard to avoid), but this edition saves an entire 5 bytes over his by taking the input as an anonymous function, with the variable name `t` chosen to occur within `intersect` (any other character in that string would have done as well). Call as `ans('yourInput')`.
> 2 votes

# Answer
# Java 8, ~~131~~ ~~129~~ 131 bytes

```
a->{java.util.Set r=new java.util.HashSet();for(String s:a)if("a->{jv.utilSe r=nwHsh();fog:\"\\cd}".contains(s))r.add(s);return r;}

```

+2 bytes again due to a bug-fix

**Explanation:**

Try it here.

```
a->{                    // Method with String-array parameter and Set return-type
  java.util.Set r=new java.util.HashSet();
                        //  The result Set
  for(String s:a)       //  Loop over the input String-array
    if("a->{jv.utilSe r=nwHsh();fog:\"\\cd}".contains(s))
                        //   If the current character is part of the source-code:
      r.add(s);         //    Add it to the Set
                        //  End of loop (implicit / single-line body)
  return r;             //  Return the result-Set
}                       // End of method

```
> 2 votes

# Answer
# Brachylog (newer), 18 bytes

```
{∈"{∈\\\"&}ˢd"&}ˢd

```

Try it online!

It's this plus the de-duplication predicate. Doesn't necessarily beat Fatalize's solution since his is in an older and very different version of the language.
> 2 votes

# Answer
# Perl 6, 38 bytes

```
<say .comb∩$*IN.comb#<>~EVAL>~~.EVAL

```

Try it online!

The generalised quine still manages to beat out the trivial program by a few bytes

# Perl 6, 41 bytes

```
say <$*. <>INabcmosy∩>.comb∩$*IN.comb

```

Try it online!
> 2 votes

# Answer
## , 12 bytes

```
34C+t"34C+tt

```

## Explanation

```
34C+t"       % Everyone in the execution sequence excluding a quote
      34C+   % Add a (") quote
          t  % Trim out everything in this string in input
           t % Trim the string so that the intersection is kept

```
> 2 votes

# Answer
# Python 3, 33 bytes

```
lambda a:{*"\"\lambd* :{}&"}&{*a}

```

Try it online!
> 2 votes

# Answer
## Python, 48 bytes

First thing I though of. It can probably be golfed more.

Input comes from sdtin. Output goes to stdout as a set object

```
print set(raw_input())&set("raw_pint se(u)\&\"")

```
> 1 votes

# Answer
# PHP, 61 bytes

```
<?=preg_filter("_<\?=[aefiglprtv$(\_[\],)\\;1\"]_",$argv[1]);

```

takes input from first command line argument.

**no regex, 74 bytes**

```
for(;""<$c=$argv[1][$i++];)if(strstr("aceghiosrtv()$<=[1]\;\"",$c))echo$c;

```

takes input from first command line argument. Run with `-nr`.

Note: `;` needs no escaping; so PHP takes the backslash before the semicolon literally.
> 1 votes

# Answer
# Java (OpenJDK 8), 58 bytes

```
s->s.filter("s->.filter(\"\\:cona)d"::contains).distinct()

```

Try it online!

Accepts the input as `Stream<String>`, whereas each character of the input is a stream element, and returns a filtered, distinct stream.
> 1 votes

# Answer
# Japt, ~~14~~ 15 bytes

My very first "proper" quine. At long fecking last!

```
oQ+"oQ+ ¬â"Q ¬â

```

Try it
> 1 votes

# Answer
# Lua, 91 bytes

Old challenge, but still lacking a Lua solution, so...

```
s=...(" s=.(\\\"):gub,fnctiod1awre"):gsub(".",function(c)c=s:find(c,1,1)and io.write(c)end)

```

Try it online!
> 1 votes

# Answer
# , 18 bytes

```
'''&()[-.'&([-.-.)

```

### How it works

```
 ''&()[-.           the character set, '' stands for '
          &         is the left operand
           ([    )  the set> itself, ignore <the input
           (   -.)  the set> except any characters in <the input
                      (the wrong ones remain)
           ( -.  )  the set itself> except <the wrong characters

```

Try it online!
> 1 votes

# Answer
# Husk, 7 bytes

```
n"n\\\"

```

Try it online!

```
n          The intersection of
 "n\\\"    the string n, \, "
           with the input.

```

I tried to work around having to escape the quote with a backslash, but that just made it longer:

# Husk, 8 bytes

```
n:'""n:'

```

Try it online!

```
n         The intersection of
  '"      the character "
 :        prepended to
  "n:'    the string n, :, '
          with the input.

```

Another attempt to eliminate backslashes, which would be two bytes shorter if it didn't need to remove duplicates:

# Husk, 7 bytes

```
uns"nsu

```

Try it online!

```
u          Without duplicate elements,
 n         the intersection of
  s        the string representation of
   "nsu    the string n, s, u
           with the input.

```
> 1 votes

# Answer
# Burlesque, 10 bytes

```
#QupIN#Qvv

```

Try it online!

Turns out the lazy way worse than doing it generally because I can't get a quote within a quote nicely. `"IN_+"'"_+IN`

```
#Q  #Push the code onto the stack
up  #Convert to string
IN  #Intersection
#Q  #Make sure a #Q is captured
vv  #Drop the resulting push

```
> 1 votes

# Answer
# brainfuck, 150 bytes

```
,[[>+>+<<-]>>[-[->>+<<]+>>]+>+[--<[-<<]>.>+>[-]]-<[-<<]>[-]<,] !"#$%&'()*/0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\^_`abcdefghijklmnopqrstuvwxyz{|}~

```

Try it online!

Support 32-126

main code(set remove dup) 62
> 1 votes

---
Tags: code-golf, quine
---


title: A decimal-based unit of time

text:
# Question
Title: A decimal-based unit of time
### Background

In 1960, the 11th General Conference on Weights and Measures defined the Système International d'Unités (SI) Units which scientists still use today.

The metre and the kilogram became standard units in that conference. These were based on powers of 10 (10, 100, 1000, etc.).

For example:

* there are *100* centimetres in one meter
* there are *1000* meters in one kilometer
* there are *1000* grams in one kilogram

### Time units

That conference also established the second as the standard unit for time. Now, this is interesting, because this is not based on powers of 10.

* There are *60* seconds in one minute
* There are *60* minutes in one hour
* There are *24* hours in one day

So let's make our own!

In our system, we will have:

* *100* seconds in one minute
* *100* minutes in one hour
* *10* hours in one day

### Your task

Given an input of a time (in 24-hour time), convert it to our system (10-hour).

**Example:**

Input: `12:34:56`

First, convert this to a number of seconds:

`(12 * 60 * 60) + (34 * 60) + 56 = 45296`

We have 100,000 seconds in our system, and in the normal system there are 86,400. We need to adjust for that:

`45296 / 86400 * 100000 = 52425.9259259259`

We round this to 52426. Note: this must be rounded.

Now, convert back to hours, minutes and seconds. This is easy because our 10-100-100 system lets us just place the colons in: `5:24:26`. This is our final answer.

**Note: you do not need to insert the colons.**

### Test cases

You can input and output in any format you want, including just an integer as the output format.

Here are some test cases:

```
Input     Output
12:34:56  5:24:26
00:00:00  0:00:00*
23:59:59  9:99:99
11:11:11  4:66:10
15:25:35  6:42:77
01:02:03  0:43:09*

```

<sup>*</sup> In these ones, you do not have to fill the minutes and seconds up to two places: i.e., you may output `0:0:0` and `0:43:9`.

**This is , so shortest answer in bytes wins!**

# Answer
> 4 votes
# 05AB1E, ~~10~~ 9 bytes

No 05AB1E yet? Let's fix that!

This is a direct port of hakr14's canvas answer.

```
60βƵOƵ7/*ò

```

Try it online!

```
60βƵOƵ7/*ò
60β           Convert input from base 60
   ƵOƵ7/      Push 125/108
        *     Multiply input and 125/108
         ò    Round

```

Thanks to @TheThonnu for this answer:

```
60β.864/ò

```

Try it online!

```
60β.864/ò
60β          Convert input from base 60
   .864      Push .864 (108/125)
       /     Divide input by 108/125
        ò    Round

```

# Answer
> 7 votes
# JavaScript (ES6), 33 bytes

Expects `(h,m,s)` and returns an integer.

```
(h,m,s)=>(h*60+m+s/60)*625/9+.5|0

```

Try it online!

### How?

By converting to minutes instead of seconds, the final ratio is:

$$\frac{60\times 100000}{86400}=\frac{625}{9}$$

This is one byte shorter than:

```
(h,m,s)=>(h*3600+m*60+s)/.864+.5|0

```

# Answer
> 4 votes
# Jelly, 11 bytes

```
ḅ60÷.864+.Ḟ

```

A monadic Link that accepts a list of non-negative integers, `[h, m, s]`, and yields a non-negative integer.

**Try it online!** Or see the test-suite.

### How?

```
ḅ60÷.864+.Ḟ - Link: list of non-negative integers, T = [h, m, s]:
ḅ60         - convert T from base sixty -> 3600*h+60*m+s = seconds
    .864    - 0.864 (seconds per "second")
   ÷        - (seconds) divide (0.864) -> "deconds"
         .  - a half
        +   - (deconds) add (a half)
          Ḟ - floor to nearest integer

```

# Answer
> 4 votes
# Python, 39 bytes

Port of `@Arnauld`'s answer, expects an input of `h, m, s` and returns an integer.

```
lambda h,m,s:round((h*60+m+s/60)*625/9)

```

Attempt This Online!

# Answer
> 4 votes
# Factor, 35 bytes

```
[ 60 * rot 60 / + + 625/9 * round ]

```

Try it online!

Expects `seconds minutes hours` as integers. Port of Arnauld's JavaScript answer.

```
      ! 56 34 12
60    ! 56 34 12 60
*     ! 56 34 720
rot   ! 34 720 56
60    ! 34 720 56 60
/     ! 34 720 14/15
+     ! 34 720+14/15
+     ! 754+14/15
625/9 ! 754+14/15 69+4/9
*     ! 52425+25/27
round ! 52426

```

# Answer
> 3 votes
# Python 3, 65 bytes

```
h,m,s=map(int,input().split())
print(round((h*3600+m*60+s)/.864))

```

Takes input as `HH mm ss` and outputs as `Hmmss`

-3 thanks to Jonathan Allan

Try it online!

# Answer
> 3 votes
# Canvas, 13 bytes

```
‾-┴‾n‾]÷×１½＋ｕ

```

Try it here!

##### Explanation:

```
‾-┴‾n‾]÷×1½+u | Full code (converted to half-width)
--------------+------------------------------------
‾-┴           | Convert input from base 60
   ‾n‾]÷      | Push 125/108
        ×     | Multiply
         1½+  | Add .5
            u | Floor

```

# Answer
> 3 votes
# C (GCC), ~~73~~ 68 bytes

*-5 bytes thanks to @Neil*

```
f(char*x){return((atoi(x)*3600+atoi(x+3)*60+atoi(x+6))*125+54)/108;}

```

Attempt This Online!

# Answer
> 3 votes
# Charcoal, 13 bytes

```
Ｉ⌊⊘⊕∕↨⁶⁰Ａ·⁴³²

```

Try it online! Link is to verbose version of code. Takes input as a list. Explanation:

```
       Ａ        Input array
     ↨          Converted from base
      ⁶⁰        Literal integer `60`
    ∕           Divided by
         ·⁴³²   Literal number `0.432`
   ⊕            Incremented
  ⊘             Halved
 ⌊              Floor
Ｉ               Cast to string
                Implicitly print

```

26 bytes for string I/O:

```
✂⪫⪪﹪%06.0f∕↨⁶⁰Ｉ⪪Ｓ:·⁸⁶⁴¦²:¹

```

Try it online! Link is to verbose version of code.

# Answer
> 2 votes
# , 19 bytes

```
0.864<.@%~0.5+60#.]

```

Try it online!

# Answer
> 2 votes
# Japt, 11 bytes

```
ì60 /.864 r

```

Try it

# Answer
> 2 votes
# Pyth, 12 bytes

```
/hyiQ60y.864

```

Try it online! Input takes a list `[hours, minutes, seconds]`, and outputs an integer.

**Explanation:**

```
/hyiQ60y.864 # whole program

    Q        # take the input
   i 60      # and convert it from base 60 to decimal
  y          # double it
 h           # increment it
/            # then integer divide it by
       y.864 # 0.864 doubled (which is 1.728)

```

# Answer
> 2 votes
# Retina 0.8.2, 40 bytes

```
\d+
$*
+`1:
:60$*
1
125$*
::
54$*
1{108}

```

Try it online! Link includes test cases. Explanation: Port of my golf to @matteo\_c's answer.

```
\d+
$*

```

Convert the hours, minutes and seconds to unary.

```
+`1:
:60$*

```

Convert from base 60, by multiplying each `1` by 60 as it passes a `:` on its way to being a number of seconds.

```
1
125$*

```

Multiply by 125.

```
::
54$*

```

Add 54.

```
1{108}

```

Integer divide by 108 and convert to decimal.

# Answer
> 2 votes
# MathGolf, 15 bytes

```
╚*j╟*++╔/☼*∞)i½

```

Inputs as three loose floats, output as a single integer.

Try it online.

**Explanation:**

Even though MathGolf has single-byte constants for `60`, `3600`, `86400`, and `100000`, it's still pretty long because it's missing base-conversion and round builtins, so those have to be done by manually.

```
╚*               # Multiply the first (implicit) input by 3600
  j              # Get the second input-float
   ╟*            # Multiply it by 60
     +           # Add the two together
      +          # Also add the third (implicit) input-float
       ╔/        # Divide this by 86400
         ☼*      # Multiply it by 100000
           ∞)i½  # Round it:
           ∞     #  Double this float
            )    #  Increase it by 1
             i   #  Truncate it to an integer
              ½  #  Integer-divide it by 2
                 # (after which the entire stack is output implicitly as result)

```

# Answer
> 0 votes
# Thunno, \\$ 11 \log\_{256}(96) \approx \\$ 9.05 bytes

```
aKAd.864/Zv

```

Attempt This Online! or verify all test cases

#### Explanation

```
aKAd.864/Zv  # Implicit input
aKAd         # Convert from a list of digits in base-60
    .864/    # Divide by .864
         Zv  # Round to the nearest integer
             # Implicit output

```

---
Tags: code-golf, math
---


title: Plus or minus polyglots!

text:
# Question
Title: Plus or minus polyglots!
Your submission must take a list of numbers (in whatever list format your language supports, or using multiple function / command-line parameters) or a string of numbers separated by any character that is not `0123456789`. In one language, it must add all of them and output the sum. In another language, it must output them *subtracted from each other in order.* Example:

```
12
5
7
2

```

In one language, it must output `26`, and in another it must output `-2`. Note that all numbers inputted will be positive integers less than `100`. There will never be more than `20` numbers provided, so you will never output greater than `2000` or less than `-1899`. Any questions? Comment below!

# Answer
> 13 votes
# Jelly / 05AB1E, 3 bytes

```
00000000: c6 71 53                                         .qS

```

This is a hexdump (xxd) of the submitted program.

Try it online!

## Jelly: Sum

Jelly uses the Jelly code page, so it sees the following characters.

```
İqS

```

Try it online!

### How it works

```
İqS  Main link. Argument: A (array)

İ    (ignored)
 q   Unrecognized token. This breaks the link; nothing to the left is executed.
  S  Take the sum of A.

```

## 05AB1E: Difference

05AB1E uses Windows-1252, so it sees the following characters.

```
ÆqS

```

Try it online!

### How it works

```
Æ     Take the difference of the input.
 q    Quit.
  S   (ignored)

```

# Answer
> 24 votes
# Python 2 / 3, 52 bytes

```
lambda l:sum(l[:1]+[x*int(1-(1/2)*4)for x in l[1:]])

```

`int(1-(1/2)*4)` returns `1` in Python 2 because `1/2` evaluates first to `0`, and then `0 * 4 = 0`.

`int(1-(1/2)*4)` returns `-1` in Python 3 because `1/2` evaluates first to `0.5`, and then `int(0.5 * 4) = int(2.0) = 2`.

# Answer
> 14 votes
# C and C++ (both from GCC), ~~81~~ ~~75~~ 73 bytes

```
int c;int f(int*a,int l){auto d=.5;c=*a++;for(;--l;a++)c+=*a-4*d**a;c=c;}

```

Takes a pointer to array and length.

**Explanation:** *still using @Steadybox' explanation :p* In C, `auto d=.5` declares an integer variable with the auto storage class (which is the default), which is then initialized to 0, whereas in C++11 it declares a double, which is initialized to 0.5.

**C - plus language:** Try it online!

**C++ - minus language:** Try it online!

# Answer
> 11 votes
# 05AB1E / Jelly, 5 bytes

```
00000000: 4f71 7f5f 2f                             Oq._/

```

Try it online! (05AB1E)
Try it online! (Jelly)

**05AB1E sees**:

```
Oq_/
```
Explanation:
```
Oq_/ 1 implicit argument.
O     Take the sum of the first input item.
 q    Quit.
  _/ Not functional.
```

**Jelly sees**:

```
Oq
_/
```
Explanation:
```
_/ Main link. Arguments: z
_/ Subtract z's elements in order.

Oq Helper link. Not functional.
```

# Answer
> 8 votes
# Actually / Jelly, 4 bytes

```
00000000: e4 81 5f 2f                                      .._/

```

This is a hexdump (xxd) of the submitted program. It cannot be tested in raw form online; TIO doesn't support the CP437 encoding.

## Actually: Sum

Actually uses CP 437, so it sees the following characters.

```
Σü_/

```

Try it online!

### How it works

```
Σ     Take the sum on the input.
 ü    Print and empty the stack.
  _   Natural logarithm. Ignored since the stack is empty.
   /  Float division. Ignored since the stack is empty.

```

## Jelly: Difference

Jelly uses the Jelly code page, so it sees the following characters.

```
ỵ¹_/

```

Try it online!

### How it works

```
ỵ¹_/  Main link. Argument: A (array)

ỵ     Unrecognized token. Splits the link.
 ¹    Identity; yield A.
  _/  Reduce (/) A by subtraction (_).

```

# Answer
> 7 votes
# Python 2 and 3, ~~44~~ 41 bytes

```
lambda l:eval(l.replace(' ','-+'[1/2>0]))

```

Takes space-separated numbers.

---

-3 bytes thanks to @JonathanAllan

Try it online: Python 2 (minus) Python 3 (plus)

# Answer
> 6 votes
# CJam/Jelly, 6 bytes

```
q~:-
S

```

### CJam

```
q~    e# Read a list from input
:-    e# Reduce by subtraction
S     e# Push a space
      e# Implicit output

```

Try it online!

### Jelly

(using UTF-8, not the Jelly code page)

`q~:-` is the helper link. Since it doesn't get called, it really doesn't matter what it does. `S` computes the sum of an array.

Try it online!

# Answer
> 6 votes
# JavaScript / Cubix, 36 bytes

```
//.!v+u;$I^@O<.Iu
a=>eval(a.join`-`)

```

# Try it!

The JavaScript function can be tested using the snippet below, the Cubix program can be tested here.

# How does this work?

## JavaScript

The first line is a line comment to JavaScript, since it starts with two slashes, so JavaScript only sees the bottom line (`a=>eval(a.join`-`)`), which takes an array as input, joins it with minus signs inbetween, and then runs that as code, resulting in the subtraction of all elements in the array.

```
let f=
//.!v+u;$I^@O<.Iu
a=>eval(a.join`-`)

console.log(f([1,2,3,4,5]))
console.log(f([3,1,4,1,5]))
```

## Cubix

Cubix sees the following cube (notice that Cubix ignores all whitespace):

```
      / / .
      ! v +
      u ; $
I ^ @ O < . I u a = > e
v a l ( a . j o i n ` -
` ) . . . . . . . . . .
      . . .
      . . .
      . . .

```

### The Beginning

The IP starts on the third line, pointing east. It hits the `'I'` command, which takes a number from the input, and pushes it to the stack. Then, it is redirected by `'^'` into the sum-loop.

### Sum-loop

I removed all characters not part of the sum loop, and replaced them by no-ops (`'.'`). The IP initally arrives on the second line, pointing east.

```
      . . .
      ! v +
      u ; $
. . . . . . I u . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

First, the `'!'` command checks the top element. If that is `0` (i.e. we have reached the end of the input), the next instruction (`'v'`) is executed, reflecting the IP out of the loop. If we have not yet reached the end of the input, we add the top two items together (`'+'`, the second item is the sum up to that point, the top item the new input). Then, the IP wraps to another face of the cube, into the `'u'` character, which causes the IP to make a u-turn, and execute a `'I'` command (read another input integer), while pointing north. The IP wraps back to the top face, skips (`'$'`) the delete instruction (`';'`) and makes another u-turn, back to the point at which we started.

### The End

If the IP is reflected out of the loop, the following characters are executed:

```
      . . .
      . v .
      . ; .
. . @ O < . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

These instructions delete the top element (which is zero), and then output the top element (the sum) as an integer. Then the `'@'` command is reached, so the program ends.

# Answer
> 4 votes
# JS (ES6), CGL (CGL Golfing Language), ~~32~~ 26 bytes

```
 x=>eval(x.join`-`)
//-⨥

```

JS does the subtraction and CGL does the addition.

## JS:

```
x=>eval(x.join`-`)

```

An anonymous function that subtracts each element in the array using `Array#reduce`.

```
//-⨥

```

A comment.

## CGL

```
 x=>eval(x.join`-`)

```

What looks like a space on the first line is actually a non-breaking space, a comment in CGL. The first line is ignored.

```
//-⨥

```

The `/`s do nothing. The `-` decrements the current stack pointer so it is pointing to input.  adds the current stack (input) together, pushes that to the next stack, and increments the current stack. It is implicitly outputted.

# Answer
> 4 votes
# JavaScript (ES6) / QBasic, ~~84~~ 83 bytes

```
'';f=x=>eval(x.join`+`)/*
INPUT a
FOR i=1 TO 2
i=0
INPUT n
a=a-n
PRINT a
NEXT i
'*/

```

Another solution with the comment hack!

JavaScript computes the sum. It takes in an array containing numbers as input. Outputs as function `return`. You can call the function like `alert(f([10,20,30]))`.

QBasic computes the difference. Repeatedly asks for input. As soon as you enter a value, it outputs the difference of all the numbers you have entered 'til the time of hitting `Enter` and again asks for input. Keeps on doing the same until the end of everything.

---

## How does it work?

In QBasic (a language of structured BASIC family; it does not require line numbers), `'` marks the beginning of a comment which goes till the end of the line. Whereas in JavaScript, it marks the start of a string. So, the whole first line is marked as a comment in QBasic but in JavaScript, the line is executed (and this line contains the JavaScript part that adds the numbers as well as a `/*` at the end which starts a comment in order to hide the rest of the QBasic code from JavaScript interpreter.)

The code from second line to second-last line contains the QBasic code to compute the difference of all the input numbers (the code is very self-explanatory).

The last line contains `'*/`. `'` causes the QBasic interpreter to interpret the following code as a comment, whereas in JavaScript, it does not have any effect as it is a part of a comment (which was started at the end of the first line). The following code (`*/`) causes JavaScript to end the comment which was started in the first line, but it is not executed in QBasic because QBasic thinks it's a part of a comment.

---

## Test Cases

**JavaScript (adds):**

```
'';f=x=>eval(x.join`+`);/*
INPUT a
FOR i=1 TO 2
i=0
INPUT n
a=a-n
PRINT a
NEXT i
'*/
console.log(f([12,5,7,2]));
```

**QBasic (subtracts):**

Go to this website. Copy paste the following code in their text-editor :

```
1 '';f=x=>eval(x.join`+`);/*
2 INPUT a
3 FOR i=1 TO 2
4 i=0
5 INPUT n
6 a=a-n
7 PRINT a
8 NEXT i
9 '*/

```

The reason why line numbers are required is that the website I mentioned only supports unstructured BASIC languages. And that website is the only decent online BASIC interpreter I could find. However, running the code present in the top of the post (the code without line numbers) should work fine in any good QBasic interpreter that supports structured BASIC and `'` as a comment-starter (few do not, most do, though).

---

## Notes

* This is my first post! I hope it's a good one!
* The QBasic part of the code does not require `END` because the interpreter will never reach it! (It will forever be stuck in the infinite loop; always asking for more input.)

# Answer
> 3 votes
# Python 2 and 3, 33 bytes

```
lambda l,*r:l+sum(r)*(1/2>0 or-1)

```

Takes input as separate parameters.

---

Python 2.
Python 3.

# Answer
> 3 votes
# Brain-Flak / Brain-Flueue, 20 bytes

```
({}<([({{}})]){}>{})

```

Try it online! (Brain-Flak) (plus)

Try it online! (Brain-Flueue) (minus)

## Explanation

The only difference between Brain-Flak and Brain-Flueue is that Brain-Flueue replaces the two stacks (last in first out) used in Brain-Flak with two queues (first in first out). Naturally this program uses this difference.

### Annotated Code

```
(                  ) Push the sum of...
 {}                   the first input,
   <            >     zero,
                 {}   the remaining sum (see below)
    ([      ])       Push the of below line
      ({{}})         Pop all the input sans first, push the sum
              {}     Pop (in Brain-Flak, this discards the negative sum,
                            in Brain-Flueue, the positive)

```

# Answer
> 0 votes
# Whispers v2/Add++, 72 bytes

```
D,f,@:,v¦Ω_
y:''
Dx,]getchar,`y,+x,`x
$f>y
> Input
>> ∑1
>> Output 2

```

Try it online! (Whispers v2)

Try it online! (Add++)

Both are encoded as UTF-8, despite Add++ having it's own code page. Whispers takes the sum, Add++ takes the difference. This assumes that both languages take input from STDIN. Add++ exits with an error after having output the difference, which is allowed by default.

## How it works (Whispers)

Whispers is very nice to polyglot, as it simply ignores every line that doesn't begin with `>`. As a result, the executed code is

```
> Input
>> ∑1
>> Output 2

```

This simply takes in input, calculates its sum and outputs it.

## How it works (Add++)

Add++ will error as soon as it reaches `> Input`, so only the stuff before that matters:

```
D,f,@:,v¦Ω_
y:''
Dx,]getchar,`y,+x,`x
$f>y

```

Taking input from STDIN is much longer in Add++ than from ARGV, but I wanted to be consistent across languages. Add++ doesn't have a builtin for reading from STDIN, aside from the `]getchar` command, which simply reads in a character (similar to brainfucks `,` command), and assigns it to the active variable (in this case `x`). Therefore, in order to read something from STDIN, we need the following structure:

```
y:''
Dx,]getchar,`y,+x,`x

```

As `]getchar` returns the empty string when it reaches the end of the input, we can use a do-while loop to read each character in. We start by declaring a variable `y` equal to the empty string. Next, we enter a do-while loop that runs until `x` is falsey (i.e. the empty string). This loop reads in a character from STDIN and concatenates it to `y`. Eventually, `y` is equal to the contents of STDIN.

Next, we define and run a function on the input:

```
D,f,@:,v¦Ω_
$f>y

```

As there is no way to evaluate a string in non-functional Add++ code, we're stuck with `y` as a string, rather than an array, which is what we need. Therefore, we have to pass the string into a function:

```
$f>y

```

The function itself is fairly basic to understand:

```
D,f,     ; Define a function which...
    @:,  ; Takes 1 argument and outputs its return value
         ; This argument is the unevaluated string input, and the : flag saves a byte when it comes to outputting the final result
    v    ; Evaluate the input (convert from a string to an array)
    ¦Ω_  ; Reduce that array by subtraction
         ; Return and output this value

```

Very simply, both languages ignore each other's code, either due to how the code is parsed, or by erroring before it's actually reached.

# Answer
> 0 votes
# Befunge-93 / Befunge-98 (FBBI), 23 bytes

```
#<&01v>-.@.+
~^#+&_^#+1

```

Try it online! (Befunge-93) (minus)
Try it online! (Befunge-98) (plus)

(Note: there must not be trailing whitespace in the input.)

### Explanation (both languages)

The control flow is the same in both languages until we reach EOF.

```
#<&01v>-.@.+
#<               # (skipped)
  &              # Get the first number
   0             # Push 0
    1            # Push 1
     v           # Go down to the next line

~^#+&_^#+1
     _           # The top 1 is nonzero, so the we go to the left
                 (begin loop)
    &            Get the next number
   +             Add it to the running total (which starts as the 0 we pushed)
 ^#              (skipped)
~                Get the next separator character
        +1       Add 1
      ^#         (skipped)
     _           The separator plus 1 is nonzero, so we keep going left
                 (repeat)

```

By the time we run out of input, the top stack element is the sum of all the numbers but the first, and the first number is underneath it. When we reach EOF, the control flow diverges, because Befunge-93 pushes `-1`, while Befunge-98 reflects the instruction pointer.

### Explanation continued (Befunge-93)

```
~^#+&_^#+1
    &         # Get the last number
   +          # Add it to the running total
 ^#           # (skipped)
~             # On EOF: push -1
        +1    # Add 1 to get 0
      ^#      # (skipped)
     _        # The top of the stack is 0, so we turn to the right
      ^       # Go up to the first line

#<&01v>-.@.+
      >       # Turn to the right
       -      # Subtract, from the first number, the sum of all the others
        .     # Print the result
         @    # End the program

```

### Explanation continued (Befunge-98)

```
~^#+&_^#+1
    &         # Get the last number
   +          # Add it to the running total
 ^#           # (skipped)
~             # On EOF: reverse direction
 ^            # Go up to the first line

#<&01v>-.@.+
 <            # Turn to the left
#             # No-op
           +  # Αdd the first number to the sum of all the others
          .   # Output the result
         @    # End the program

```

# Answer
> 0 votes
# Python 3 / Javascript, 55 bytes

```
1//1;"""
f=(l)=>eval(l.join`-`)//""";f=lambda l:sum(l)

```

Javascript function taken from Luke's Javascript / Cubix answer. Python function is trivial. Works by abusing the fact that // is an operator in python and a line commentor in javascript, and then using """ to comment out the javascript section.

## Running the code

In Python:

```
1//1;"""
f=(l)=>eval(l.join`-`)//""";f=lambda l:sum(l)

print(f([1, 2, 3]))

```

In Javascript:

```
1//1;"""
f=(l)=>eval(l.join`-`)//""";f=lambda l:sum(l)

console.log(f([1, 2, 3]));

```

# Answer
> 0 votes
# JavaScript ES6/ES10, 29 bytes

```
x=>eval(x.join(x.at?'+':'-'))

```

Try it online!

Decide if `Array.prototype.at` exist

# x86 16-bit/32-bit, 15 bytes

```
    lodsw
    xchg ax, dx
    jmp b
a:  lodsw
    mov bx, 0 ; skip next instruction in 32-bit
    neg ax
    add dx, ax
b:  loop a
    ret

```

---
Tags: code-golf, math, number, arithmetic, polyglot
---


# Question
Title: Make a Hello World using as many bytes as possible
Write a program that outputs the exact string:

```
jan ale o, toki!

```

*("Hello, world" but in toki pona to prevent builtins.)*

with an optional trailing newline.

Additionally when all copies of any one byte present in your program are removed the program must fail to produce a correct output no matter what byte is selected.

To fail it just has to produce a wrong result, it doesn't matter whether it errors or not. Wrong doesn't necessarily mean different, just wrong. So using a different output format or dropping the optional trailing newline are not failure.

You are not allowed to read your own source code.

## Scoring

Answers will be scored on two properties, the first is the number of distinct bytes, used (max being 256) in the program, with higher score being better.

Since it shouldn't be too hard to achieve the maximum for your choice of language in the first category the second category is good old . Answers are scored then in total number of bytes with lower being better.

# Answer
# Jelly, 256 bytes, score 256

Crushed my other answer :)

```
⁾j¡»“b¢£¥¦©¬®µ½¿ÆÇÐÑa×ØŒÞßæçðıȷñ÷øœnþ"#$&'()*-.078 :;<=>?@ABCEFGHḥIJKLMNPQRSTUVWlXYZ[\]^_`cdfghempqruvwxyz{|}~Ɲ¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼oƁƇƊƑƓƘⱮƤƬƲȤɓƈɗ,ƒɠɦƙɱɲƥʠɼʂƭʋȥẠṣḄḌẸḤỊḲḶṂṆṚṢṬỤṾtẈỴẒȦḂĊĖḞĠİĿṀṄȮḳṘṠṪẆẊẎŻạḅḍẹịḷṃkṇọṛṭ§ẉỵẓȧḃċḋėḟiġḣŀṁṅȯṗṙṡṫẇẋẏż!”s9123456DḊṖ+/¤Ḣ€O’‘%⁽«ÄỌ

```

**Try it online!**

Or try to remove any byte \- this will remove the byte at the nth position and evaluate the result as a niladic link.

Some notable byte positions...

* removing any of \\$217\\$ to \\$231\\$ (`ġḣŀṁṅȯṗṙṡṫẇẋẏż!`) will print `jan ale o, toki` without the final `!`
* removing \\$1\\$ () will, when run as a full-program, hang waiting for input, and, if an input is given, it will then error comparing an integer to a string (on TIO it will give an EOF error with no pre-prepared input).
* removing \\$241\\$ (`D`) will take about 12 seconds but will print `j`
* removing \\$256\\$ () will print a list of integers, the ordinal values of `jan ale o, toki!`.

#### The base program

A large portion of the code is:

```
“b¢£¥¦©¬®µ½¿ÆÇÐÑa×ØŒÞßæçðıȷñ÷øœnþ"#$&'()*-.078 :;<=>?@ABCEFGHḥIJKLMNPQRSTUVWlXYZ[\]^_`cdfghempqruvwxyz{|}~Ɲ¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼oƁƇƊƑƓƘⱮƤƬƲȤɓƈɗ,ƒɠɦƙɱɲƥʠɼʂƭʋȥẠṣḄḌẸḤỊḲḶṂṆṚṢṬỤṾtẈỴẒȦḂĊĖḞĠİĿṀṄȮḳṘṠṪẆẊẎŻạḅḍẹịḷṃkṇọṛṭ§ẉỵẓȧḃċḋėḟiġḣŀṁṅȯṗṙṡṫẇẋẏż!”

```

Which is a string with runs of \\$15\\$ bytes:

```
“b..a..n.. ..ḥ..l..e..Ɲ..o..,..ṣ..t..ḳ..k..i..!”

```

Here each of the \\$15\\$ occurrences of `..` represents \\$14\\$ filler bytes that are simply placed arbitrarily (it isn't guaranteed that any placement of the remaining \\$210\\$ bytes would do but most will).

Replacing that for brevity with `“data”` the code is:

```
⁾j¡»“data”s9123456DḊṖ+/¤Ḣ€O’‘%⁽«ÄỌ - Link: no arguments
⁾j¡                                - list of characters = "j¡"
    “data”                         - list of characters = the data described above
   »                               - maximum (vectorises)
                                     -> replaces the first character with 'j'
                                        call this newData
                       ¤           - nilad followed by link(s) as a nilad:
           9123456                 -   9,123,456
                  D                -   to decimal digits -> [9,1,2,3,4,5,6]
                   Ḋ               -   dequeue -> [1,2,3,4,5,6]
                    Ṗ              -   pop -> [1,2,3,4,5]
                      /            -   reduce with:
                     +             -     addition -> 1+2+3+4+5=15
          s                        - split (newData) into slices of length (15)
                        Ḣ€         - head of each -> "jan ḥleƝo,ṣtḳki!"
                          O        - ordinals
                           ’       - decrement -> ordials - 1
                            ‘      - increment -> ordinals
                                     -> [106,97,110,32,7717,108,101,413,111,44,7779,116,7731,107,105,33]
                              ⁽«Ä  - 127
                             %     - (ordinals) modulo (127)
                                     -> [106,97,110,32,97,108,101,32,111,44,32,116,111,107,105,33]
                                 Ọ - cast to characters
                                     -> "jan ale o, toki!"

```
> 7 votes

# Answer
# Julia 1.0, score ~~126~~ 242, (~~269~~ 259 bytes)

```
lowercase("
�
#\$&'./;<=?%6890+-gh@BCDFGHJKM࿋ᣤ⢌㯙䡚嶃氼甬蟦鍂ꕇ돲츛톩’ñĉūƹǪȀɠʑˎ̿ͥξυЖѓҁӭԜծ֘׳خٓھۧܞݩސߵPQRSUVWXYZ^_`bdfmquvxyz{}~jAN aLE O, TokI!"[213:4*57])|>print

```

Try it online!

(the first 2 characters of the long string are `\r\0`)

Check the score (+1 because TIO turns `\r` into `\n`)

-10 bytes with Jakque's idea

### hexdump

```
00000000  6c 6f 77 65 72 63 61 73  65 28 22 0d 00 01 02 03  |lowercase(".....|
00000010  04 05 06 07 08 09 0a 0b  0c 0e 0f 10 11 12 13 14  |................|
00000020  15 16 17 18 19 1a 1b 1c  1d 1e 1f 23 5c 24 26 27  |...........#\$&'|
00000030  2e 2f 3b 3c 3d 3f 25 36  38 39 30 2b 2d 67 68 40  |./;<=?%6890+-gh@|
00000040  42 43 44 46 47 48 4a 4b  4d f0 bf bb bd f1 a8 9d  |BCDFGHJKM.......|
00000050  9e f2 88 b7 b4 f3 a7 b5  ba e0 bf 8b e1 a3 a4 e2  |................|
00000060  a2 8c e3 af 99 e4 a1 9a  e5 b6 83 e6 b0 bc e7 94  |................|
00000070  ac e8 9f a6 e9 8d 82 ea  95 87 eb 8f b2 ec b8 9b  |................|
00000080  ed 86 a9 ee 84 8a ef 90  97 c2 92 c3 b1 c4 89 c5  |................|
00000090  ab c6 b9 c7 aa c8 80 c9  a0 ca 91 cb 8e cc bf cd  |................|
000000a0  a5 ce be cf 85 d0 96 d1  93 d2 81 d3 ad d4 9c d5  |................|
000000b0  ae d6 98 d7 b3 d8 ae d9  93 da be db a7 dc 9e dd  |................|
000000c0  a9 de 90 df b5 50 51 52  53 55 56 57 58 59 5a 5e  |.....PQRSUVWXYZ^|
000000d0  5f 60 62 64 66 6d 71 75  76 78 79 7a 7b 7d 7e 7f  |_`bdfmquvxyz{}~.|
000000e0  6a 41 4e 20 61 4c 45 20  4f 2c 20 54 6f 6b 49 21  |jAN aLE O, TokI!|
000000f0  22 5b 32 31 33 3a 34 2a  35 37 5d 29 7c 3e 70 72  |"[213:4*57])|>pr|
00000100  69 6e 74                                          |int|

```

### Explanation

```
lowercase("long string...jAN aLE O, TokI!"[213:4*57])|>print

```
* if a byte is missing in the long string, 4\*57 will be greater than the length of the string and will error, alternatively, it will produce an incorrect unicode sequence and error as well
* a byte missing in the numbers (213 and 4\*57) will give an other substring or error
* a byte missing elsewhere will be a syntax error or an undefined function
* `lowercase` allows to mix the case in the Hello world and thus reduce the length of the string
* `213:4*57` was found by brute-force

I believe this is all I can get with valid UTF-8 sequences

this is getting close to optimal, with only 17 repeated bytes
> 5 votes

# Answer
# Husk, ~~256~~ 256 bytes

*Edit: removed '`\`' character from the filler string, which was otherwise interpreted as an escape signal and not counted towards its length (and so would be deletable).*

```
↓₁-237+6L"¤½↕↑↔←→∟¡¿‼…‰‡√≤≥±∂∫∞≈≠≡⌐÷× #$%&`'()*./014589:;=>?@ABCDEFGHIJKMNOPQRSTUVWXYZ[]^_bcdefghiklmnopqrstuvwxyz{|}~·₂₃₄₅₆₇₈₉⌈⌉⌊⌋ΓΔΘΛΞΠΣΦΨΩαβγδεζηθλμξπρςστφχψω⁰¹²³⁴⁵⁶⁷⁸⁹¢£€¥ƒ´▲▼►◄§ḂĊḊĖĠḢİĿṀṄȮṖṘṠṪẆẊẎŻȧḃċḋėḟġḣıȷŀṁṅȯṗṙṡṫẇẋẏżÄËÏÖÜŸØäëïöüÿø◊□¶«»
¨\ja¬Ȧ¦₀,†Ḟ<!

```

Try it online!

First attempt using a long compressed string was quickly debunked, so here's one without compression of the filler string...

```
↓₁              # drop X characters from the compressed string on next line
                # which is ¨\ja¬Ȧ¦₀,†Ḟ<!¨ encoding "\jan ale o, toki!"

                # Calculate X as:
         L"     # Length of this non-compressed filler string
                # (containing all the other Husk codepoints),
       +6       # plus 5,
   -237         # minus 257:
                # X should equal 1 (to remove the leading '`' character;
                # deletion of any character from the filler string yields X=0,
                # so the '\' is printed.

```
> 4 votes

# Answer
# Zsh, score 256 (269 total bytes)

```
grep -Eax .{240}<<X|cut -f1
jan ale o, toki!    "#$%&'()*+/356789:;=>?@ABCDFGHIJKLMNOPQRSTUVWYZ[]^_\`bdhmqsvwyxz~...............................................................................................................................................................
```

Attempt This Online!

Those `.`s are all unprintables, so here's a hexdump:

```
00000000: 6772 6570 202d 4561 7820 2e7b 3234 307d  grep -Eax .{240}
00000010: 3c3c 587c 6375 7420 2d66 310a 6a61 6e20  <<X|cut -f1.jan
00000020: 616c 6520 6f2c 2074 6f6b 6921 0922 2324  ale o, toki!."#$
00000030: 2526 2728 292a 2b2f 3335 3637 3839 3a3b  %&'()*+/356789:;
00000040: 3d3e 3f40 4142 4344 4647 4849 4a4b 4c4d  =>?@ABCDFGHIJKLM
00000050: 4e4f 5051 5253 5455 5657 595a 5b5d 5e5f  NOPQRSTUVWYZ[]^_
00000060: 5c60 6264 686d 7173 7677 7978 7a7e 0001  \`bdhmqsvwyxz~..
00000070: 0203 0405 0607 080b 0c0d 0e0f 1011 1213  ................
00000080: 1415 1617 1819 1a1b 1c1d 1e1f 7f80 8182  ................
00000090: 8384 8586 8788 898a 8b8c 8d8e 8f90 9192  ................
000000a0: 9394 9596 9798 999a 9b9c 9d9e 9fa0 a1a2  ................
000000b0: a3a4 a5a6 a7a8 a9aa abac adae afb0 b1b2  ................
000000c0: b3b4 b5b6 b7b8 b9ba bbbc bdbe bfc0 c1c2  ................
000000d0: c3c4 c5c6 c7c8 c9ca cbcc cdce cfd0 d1d2  ................
000000e0: d3d4 d5d6 d7d8 d9da dbdc ddde dfe0 e1e2  ................
000000f0: e3e4 e5e6 e7e8 e9ea ebec edee eff0 f1f2  ................
00000100: f3f4 f5f6 f7f8 f9fa fbfc fdfe ff         .............

```

Needs to be run with `LC_ALL=C`, because otherwise `grep`/`cut`/`Zsh` get confused by broken Unicode.

## Explanation

`<<X` takes the rest of the file and passes it to `grep`, which searches for a line containing 241 characters. `-E` is necessary to activate the `{}` quantifier, `-a` forces processing of the input even though it is "binary" not "text", and `-x` ensures the whole line has to match, not just a substring.

If it matches (i.e. no characters on the second line have been removed), this is passed to `cut`, which outputs only the `1`st `f`ield (tab-separated).

If any character on the first line (including the newline) is removed, the search command will break or the pattern won't be matched.

`\` escapes the ```, because even in a heredoc (`<<X`), some expansions (importantly ````) are still processed, and otherwise it would be unmatched.

`x` is duplicated in the second line even though it's already used in the first line, because if it's removed from the `grep` command then the pattern still matches, but we need it to disallow any of the digits `240` from being removed (otherwise there is always a 20-character substring of that line, or whatever)
> 2 votes

# Answer
# Charcoal, 141 bytes, score 97

```
⍘⍘!ltoojjjtnn!!iiea,teoikneleaa ¦ !,aeijklnot¦ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

Try it online! Explanation: The string `!ltoojjjtnn!!iiea,teoikneleaa`  is interpreted in the custom base  `!,aeijklnot` and then converted to the custom base of printable ASCII. Removing any of the characters in the custom base will obviously prevent them from being output, but also removing any of the other printable ASCII will scramble the result, while removing the either of the two non-ASCII characters will break the Charcoal program as a whole.
> 2 votes

# Answer
# \>\<\>, 297 bytes, score 256

```
'!ikot ,o ela naj'!;v
"#$%&()*+-./01234567o;
89:<=>?@ABCDEFGHIJKL ;
MNOPQRSTUVWXYZ[\]^_` ;
bcdfghmpqrsuwxyz{|}~ ;
.................... ;
.................... ;
.................... ;
.................... ;
.................... ;
.................... ;
.................... ;
.................... ;

```

Try it online!

(replace the dots with all the unprintable ascii)

The main idea is fairly simple, removing any byte will block the "print corridor" with the termination character `;`

Some notable exceptions:

* Removing the letters in the original phrase will crash the instruction pointer into `J`, `K` or `L`
* Removing a single quote will crash the instruction pointer at `k`
* Removing `;` will crash the instruction pointer at `L`
* Removing newlines or `v` will cause no output to be written.
> 1 votes

# Answer
# Python 3, 243 unique bytes, ~~265~~ 261 bytes

```
B=0
input("
	#$%&'*+-/25789;<>?@CDFGHMPQRSUVWXYZ^_`bcdghjkmqsvyz{|}~ŸÜĜŜƜǜȜɜʜ˜̜͜ΜϜРѡҢӣԤե֦קب٩ڪ۫ܬݭޮ߯ఀ᱁Ⲃ㳃䴄嵅涆緇踈鹉꺊뻋켌퍽ￏ_JaN ALE \x4f, TOKI!".lower()[136:])

```

Try it online!

Score ! (the score shows 242 because tio interprets `\n` and `\r` the same way)

## Note :

as MarcMush pointed, TIO link doesn't like unicodes `\U10xxxx`. To make my link works, I changed  by `_` in the code.

## Explanation:

the code is equivalent to :

```
B=0
input("""<bunch of useless stuff>JaN ALE \x4f, TOKI!""".lower()[<index>:])

```
* store the wanted string upper case and lower it allows to reduce the number of bytes as they would have been stored in the code anyways. I also used `\x4f` instead of `O` to save 1 byte
* if ant byte is removed from the first line, the program will crash due to a syntax error or a Name error.
* if any byte is removed from the string, or the slice, the portion written would not be the correct one.
* if any other byte is removed, the code will crash
> 1 votes

# Answer
# Jelly, 256

```
“¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi“jklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮ“ṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>“?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^“_`abcdefghijklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂ“ĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./01“23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝ“ƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚ“ṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+“,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVW“XYZ[\]^_`abcdefghijklmnopqrstuvw“xyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟ“ġḣŀṁṅȯṗṙṡṫẇẋẏż¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`“abcdefghijklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖ“ṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:“;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[”Ẉ‘’Ọ«“ŀW»

```

A full program using all 256 bytes in Jelly's code-page.

I am very confident that **this can be beaten** since it is a naive attempt using a run-length encoding of the ordinals, which stands at 1368 bytes!

For 251 of the bytes the program will run successfully as a monadic Link - see them all here.

For the other five see these full programs:
removing  fails,
removing  fails,
removing  fails,
removing  fails, and
removing `«` produces text, but must be run as a full-program
> 0 votes

# Answer
# x86 .COM , 256/256 byte,

```
00000000: bff2 01b8 9190 2905 6681 4506 9594 9392  ......).f.E.....
00000010: b409 575a 83ea 03fe 8d2a ffcd 22c3 ????  ..WZ.....*.."...
000000e0: ???? ???? ???? ???? ???? ???? ???? ??6a  ...............j
000000f0: 616e b1f1 6c65 206f 978b e0dc 6b69 2124  an..le o....ki!$

```

asm:

```
    org 100h
    mov di, 0x1F2
    mov ax, 0x9091
    sub [di], ax
    add [di+6], dword 0x92939495
    mov ah, 9
    push di
    pop dx
    sub dx, 3
    dec byte [di-0x1F2+k+1]
k:  int 0x22
    ret
    db 0x1EF-$ dup ?
    db 'j'
    dw 'an'
    dw ' a'+0x9091-0x10000
    dd 'le o'
    dd ', to'-0x92939495
    dd 'ki!$'

```

Fill the `db 0x1EF-$ dup ?` with all left bytes

Maybe it's possible to make one with MZ head
> 0 votes

---
Tags: code-golf, code-challenge, kolmogorov-complexity, source-layout, radiation-hardening
---


title: Seventy Seven Sevens

text:
# Question
Title: Seventy Seven Sevens
Given a number `n` and an upper limit `l` list the numbers that can be created by multiplying two or more numbers consisting of **only sevens** of length `n` or less that are less than `l`. A161145 is close to this challenge, however, you will NOT be including the 7, 77, 777, 7777, 77777, etc..

# Examples

**`n=anything, l<49` would result in:**

```
[]

```

**`n=1, l=49` would result in:**

```
7*7=49

f(1,49)=[49]

```

**`n=1, l=343` would result in:**

```
7*7   =49
7*7*7 =343

f(1,343)=[49,343]

```

**`n=2,l=6000` would result in:**

```
7*7    =49
7*7*7  =343
7*7*7*7=2401
7*77   =539
7*7*77 =3773
77*77  =5929

f(2,6000)=[49,343,539,2401,3773,5929]

```

**`n=3, l=604000` would result in:**

```
[49, 343, 539, 2401, 3773, 5439, 5929, 16807, 26411, 38073, 41503, 59829, 117649, 184877, 266511, 290521, 418803, 456533, 603729]

```

Etc...

# Rules

1. You **do not** have to output intermediate steps, this was done for clarity.
2. Output can be as an array or separated by any character (even newlines).
3. Output must be in numerical order, lowest to highest.
4. To make the title relevant, highest `n` that must be handled is `n=77` (if you can't handle that high, note why - language restrictions are acceptable, laziness is not). This limitation is to hinder those looking to build the entire superset in memory.
5. If TIO cannot run `n=77` for your code, explain what specs were required to achieve `n=77`.
6. For a product to be valid it must consist of at least 2 numbers.
7. This is lowest byte-count will be deemed victorious.
8. You may choose the list to contain items less than `l` or less than/equal to `l`.
9. **BONUS**: If your code is exactly 77 bytes, kudos from me; worthless, I know.

# Answer
> 1 votes
# 05AB1E, 19 bytes

```
L7×1¸ì©IF®âPD²‹Ïê®K

```

Try it online!

**Explanation**

Very inefficient. TIO link performs `ceil(l^(1/7))` iterations instead of the `l` iterations used in the golfed version to easier test large testcases.

```
L7×                   # create the list ['7', '77', '777' ...]
                      # with the final item having n 7's
   1¸ì©               # prepend a 1 and store a copy in register
       IF             # l times do:
         ®â           # cartesian product between current list and the list in register
           P          # product of each sublist
            D²‹Ï      # keep only numbers smaller than l
                ê     # remove duplicates and sort
                 ®K   # remove 1, 7, 77, 777 ... from the list

```

# Answer
> 7 votes
# Jelly, ~~21~~ ~~20~~ ~~19~~ 18 bytes

```
R7ẋḌµ;ŒċP€⁹f€FµÐLḟ

```

Note that the output doesn't match the OP's. I've left a comment.

Try it online!

### How it works

```
R7ẋḌµ;ŒċP€⁹f€FµÐLḟ  Main link. Left argument: n. Right argument: l

R                   Range; yield [1, ..., n].
 7ẋ                 Times; yield [[7], ..., [7] * n].
   Ḍ                Undecimal; yield s := [7, 77, ...].
    µ         µÐL   Begin a new chain with argument s and call the chain between
                    until the results no longer chain.
                    Return the last unique result.
      Œċ            Combinations; return all unordered pairs in integers in the
                    return value.
     ;              Concatenate the return value and its pairs.
        P€          Take the product of each individual integer and each pair in
                    the result.
          ⁹f€       Filter each; for each j in [1, ..., l], intersect [j] with the
                    array of products. The result is sorted and contains no
                    duplicates.
                 ḟ  Filterfalse; remove the elements of s from the result.

```

# Answer
> 6 votes
# Python 2, ~~116~~ ~~113~~ 109 bytes

```
n,l=input()
r=t={1}
exec't|={10**n/9*7};n-=n>1;r=r|{x*y for x in r for y in t if l/x/y};'*l
print sorted(r-t)

```

Note that TIO doesn't have enough memory for the last test case.

Try it online!

# Answer
> 4 votes
## JavaScript (ES6), ~~103~~ 101 bytes

Takes input in currying syntax `(n)(l)`.

```
n=>l=>(a=[],g=(n,m,p,i)=>(p>l||g(n,m,(a[i>1?p:a]=p)*m,-~i),--n?g(n,m+7,p,i):a.filter(n=>n)))(n,'7',1)

```

### Test cases

The last test case may take a few seconds to complete.

```
let f =

n=>l=>(a=[],g=(n,m,p,i)=>(p>l||g(n,m,(a[i>1?p:a]=p)*m,-~i),--n?g(n,m+7,p,i):a.filter(n=>n)))(n,'7',1)

console.log(f(1)(49))
console.log(f(1)(343))
console.log(f(2)(6000))
console.log(f(3)(604000))
```

# Answer
> 4 votes
# Ruby, ~~89~~ 86 bytes

A recursive solution.

-3 bytes by remembering that anything times 0 is 0.

```
f=->n,l,b=1{n*l>0?(f[n,l/k=eval(?7*n),b*k]+f[n-1,l,b]+(b>1&&l>=k ?[k*b]:[])).sort: []}

```

Try it online!

# Answer
> 4 votes
# PHP, 142 Bytes

```
$r=[];for([,$n,$l]=$argv;$n--;)f($v[]=$z.=7);function f($t){global$v,$l,$r;while($c=$t*$v[+$i++])$l<$c?:f($c)&$r[$c]=$c;}sort($r);print_r($r);

```

-5 Bytes removing `$r=[];` and replace `sort($r);` with `@sort($r);`

Online Version

Expanded

A recursive function make all permutations including the limit

```
$r=[];
for([,$n,$l]=$argv;$n--;)
  f($v[]=$z.=7);
function f($t){
    global$v,$l,$r;
    while($c=$t*$v[+$i++])
      $l<$c?:f($c)&$r[$c]=$c;
}
sort($r);
print_r($r);

```

PHP, 145 Bytes

```
for([,$n,$l]=$argv;$n;)$t[]=str_pad(7,$n--,7);for(;$l>=$i+=49;$v>1?:$u[]=$r)for($v=$i,$r=!$c=0;$d=$t[$c];)$v%$d?$c++:($v/=$d)&$r*=$d;print_r($u);

```

Expanded

a loop till including the limit check every value that is divisible by 49

```
for([,$n,$l]=$argv;$n;)
  $t[]=str_pad(7,$n--,7);
for(;$l>=$v=$i+=49;$v>1?:$u[]=$r)
  for($r=!$c=0;$d=$t[$c];)
    $v%$d?$c++:($v/=$d)&$r*=$d;
print_r($u);

```

Online Version

a few bytes more and an associative array can be created key the number and as value an array of the used sevens

```
for([,$n,$l]=$argv;$n;)
  $t[]=str_pad(7,$n--,7);
for(;$l>=$v=$i+=49;$v>1?:$u[array_product($r)]=$r)
  for($r=[],$c=0;$d=$t[$c];)
    $v%$d?$c++:($v/=$d)&$r[]=$d;
print_r($u);

```

Online Version

# Answer
> 3 votes
# PHP, ~~128 125 130 129 127~~ 123 bytes

will work up to 22 `7`s but will round larger values (7\**23 is floating point on a 64 bit machine).

3 bytes saved by Jörg, 3 by me, ~~5 4~~ 1 added to avoid warning for empty results.

```
for([,$c,$z]=$argv,$n=$c+1;$c<$z;$p<$z&&$r[$p]=$p)for($b=$c+=$p=1;$b|0;$b/=$n)$p*=str_pad(7,$b%$n,7);@sort($r);print_r($r);

```

takes input from command line arguments; run with `-nr` or try it online.

**breakdown**

```
for([,$c,$z]=$argv,$n=$c+1;         # $z=L, $n=N+1
    $c<$z;                          # loop $c from N to L-1:
    $p<$z&&$r[$p]=$p                    # 2. if product is < L, add to array
)                                       #    (key=val to avoid duplicates)
    for($b=$c+=$p=1;$b|0;$b/=$n)        # 1. loop $b through ++$c as base-N+1 number
        $p*=str_pad(7,$b%$n,7);             # take each base-N+1 digit as length
                                            # for a streak of 7s as factor
        // (str_pad is 1 byte shorter than str_repeat and saves 3 by ensuring positive $p)
@sort($r);                          # sort array (muted to avoid warning for empty result)
print_r($r);                        # print array

```

# Answer
> 3 votes
# Pyth, 22 bytes

```
JsM._*\7Eu@s*LR+JGJSQJ

JsM._*\7E
        E               second input
     *\7                repeat "7" as many times as the above
   ._                   all prefixes of above
 sM                     convert each to integer
J                       store list as J

         u@s*LR+JGJSQJ
         u              repeat the following until results not unique
                     J  starting from G = J
                        at each iteration, G is the current value
               +JG      append G to J
                  J     J
            *LR         multiply the elements of the above two, vectorizing each
           s            flatten list
          @        SQ   intersect with [1,2,3,...,first input]
                        this takes elements from [1,2,3,...,first input] and
                        check if each element is in the previous list
                        which ensures the result is sorted and unique

```

Try it online!

## Specs

* Input: `l[newline]n`
* Output: `array containing the sorted result`

# Answer
> 3 votes
# Brachylog, 28 bytes

```
h>.ḋ{p~c×ᵐ{=h7&l}ᵐobt≤~t?∧!}

```

There's a lot of scope for improvement in the language itself, here; quite a few things I wrote look like they'd be obviously improvable with some changes to the language's design. This is the shortest way I've found with the current version. I may well make some suggestions for Brachylog which would make this program more efficient, shorter, and more readable.

Very, very slow; TIO times out even on the simplest possible nontrivial answer, so there's not much point in providing a TIO link. I've verified this program by running it locally.

This is a function (not a full program), whose output is a generator (as opposed to a list). Add `.w⊥` to the end of the function if you want to see all outputs, rather than just the first. (Note that this doesn't really matter in practice, because as the program is too slow for TIO anyway, you have to run it locally, and the local Brachylog interpreter runs in a REPL which can describe a generator just fine.)

## Explanation

```
h>.ḋ{p~c×ᵐ{=h7&l}ᵐobt≤~t?∧!}
  .                           The desired output is
h>                            a number less than the first input
   ḋ p                        such that taking its prime factors in some order,
      ~c                      partitioning them,
        ×ᵐ                    and taking the product of each partition
          {     }ᵐ            produces a number for which each digit
           =h7                is composed only of 7s
              &l              and for which the lengths of those numbers
                  o           are in sorted order
                    t         and the last element
                   b          (which is not also the first element)
                     ≤        is less than or equal to
                      ~t?     the last input.
                         ∧    (Delete an unwanted implicit constraint.)
   ḋ{                     !}  Output each number only once.

```

# Answer
> 2 votes
# Bash + GNU utilities, 108

```
seq -f3o%gp $2|dc|sed -r "/0|1{$1}/d;s/./&7/g;s/1//g;s/2/*/g;/[*]/!d;s/^/a=7/;s/$/;if(a<=$2)a;/"|bc|sort -un

```

Try it online. TIO takes about a minute for the last testcase. My results match @Dennis's.

# Answer
> 1 votes
# Pyth -- ~~57~~ ~~51~~ ~~49~~ 42 bytes

```
FY}2eQKYJv*\7hQWJIqYJBW!%KJ=/KJ)=/JT)Iq1KY

```

Try it

# Answer
> 0 votes
# JavaScript (Node.js), ~~94~~ ~~91~~ 88 bytes

```
n=>l=>(X=[]).filter(g=(i,j=1,k)=>j>l|i[n]||(X[g(i+7,j,k)|g(i,j*i,-~k),k>1&&j]=j),l=g`7`)

```

Try it online!

```
n=>l=>         // input
(X=[]).filter( // X stores index=results
g=(i,j=1,k)=>  // recurse             Reuse of g for filter:
j>l|i[n]||     // out of range        49>1|49[n] (true)
(X[g(i+7,j,k)|g(i,j*i,-~k),k>1&&j]=j)
               // k<=1: X[false]=j, ignored
               // k>1: X[j]=j
,l=g`7`)       // First call [0/1]|[0/1]||1 ==1

```

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