title: Previous Fibonacci number

text:
# Question
Title: Previous Fibonacci number
The sequence of Fibonacci numbers is defined as follows:

\\$ F\_0 = 0 \\ F\_1 = 1 \\ F\_n = F\_{n-1} + F\_{n-2} \\$

Given a Fibonacci number, return the previous Fibonacci number in the sequence. You do not need to handle the inputs \\$ 0 \\$ or \\$ 1 \\$, nor any non-Fibonacci numbers.

Errors as a result of floating point inaccuracies are permitted.

This is , so the shortest code in bytes wins.

# Answer
> 19 votes
# Vyxal, 4 bytes

```
kg/ṙ

```

Try it Online!

Port of Unmitigated's JavaScript answer

```
  /  # Divide by...
kg   # Phi
   ṙ # Round

```

# Answer
> 15 votes
# JavaScript, ~~21~~ 17 bytes

```
n=>n*5**.5-n+1>>1

```

Try it online!

-4 bytes thanks to att.

# Answer
> 13 votes
# , ~~23~~ ~~22~~ 20 bytes

*Edit: -1 byte thanks to pajonk, then -2 bytes thanks to att*

```
\(x)(x*5^.5-x+1)%/%2
```

Attempt This Online!

The ratio between consecutive fibonacci numbers famously converges towards the golden ratio phi, equal to `(1+5^.5)/2`.
This is sufficiently accurate that rounding produces the correct value for all fibonacci numbers, including even the second `1` at the start which we don't need to handle here.

(Edit after reading some other answers: this was independently-derived, but is also the approach taken by Luis Mendo and unmitigated)

# Answer
> 11 votes
# , 27 bytes

```
\(x){while(x>T)T=F+(F=T);F}
```

Attempt This Online!

Similar to this answer, iterates through the Fibonacci sequence until `T==x` and returns `F`.

# Answer
> 11 votes
# x86-64 assembly, ~~13~~ 12 bytes

```
6a 01 58 99 92 01 c2 39 fa 75 f9 c3

```

In assembly:

```
previous:
    push 1
    pop rax
    cdq     # zeroes rdx
previous_loop:
    xchg eax,edx
    add edx,eax
    cmp edx,edi
    jne previous_loop
    ret

```

Try it online!

Uses the usual calling convention of taking the first argument in `rdi` and returning in `rax`. It's also valid x86-32, just with `edi` and `eax` instead.

It's pretty simple- it just explicitly computes Fibonacci numbers and returns if the new number is equal to the input. At the end of a loop, `rdx` contains the next Fibonacci number and `rax` contains the previous. If `rdx` is equal to the input `rdi`, then the loop terminates (and thus `rax`, the previous number, is returned). Otherwise the two are swapped, and the loop begins again.

This uses 32-bit registers to save a few bytes, so it only works up to the 47th Fibonacci number, `2971215073`. It can be expanded to work with 64-bit numbers by changing all the registers to 64-bit, at the cost of 2 bytes:

```
6a 01 58 99 48 0f c1 c2 48 39 fa 75 f7 c3

```

The added bytes are the REX.W (`0x48`) prefix that swaps the operand size to 64-bit. `xchg rax,rdx; add rdx,rax` is also replaced with `xadd rdx,rax`, which is shorter because it uses one fewer REX.W prefix.

-1 byte thanks to @PeterCordes.

# Answer
> 9 votes
# Factor \+ `math.unicode`, ~~21~~ ~~19~~ ~~18~~ 14 bytes

```
[ φ / round ]

```

Try it online!

-4 thanks to @DominicvanEssen!

Divide the input by the golden ratio and round the result.

# Answer
> 9 votes
# C(gcc), ~~57,55,53,50,45~~, 36 bytes

```
x;y;f(a){for(x=y=1;y-a-x;y+=x=y-x);}

```

Naive approach based on calculating all previous Fibonacci numbers, breaking when we reach the input.

Try it here

Edit: Thanks for Neil, golfing ~~2~~ 5 bytes.

Edit2: Thanks Dominic van Essen for golfing an other 5 bytes.

Edit3: Thanks att for golfing 9 bytes.

# Answer
> 8 votes
# Python 3, 41 bytes

```
f=lambda n,a=0,b=1:n-b and f(n,b,a+b)or a

```

Try it online!

# Answer
> 7 votes
# Python 3, ~~29~~ ~~28~~ ~~27~~ 24 bytes

*The footer uses @Noodle9's checker code*.

*1 byte saved thanks to @Chris!*

*3 more bytes off thanks to Albert.Lang!*

Function that returns an integer-valued `float`. It fails for large inputs due to floating-point inaccuracies.

```
lambda n:~n*(1-5**.5)//2

```

Try it online!

# Answer
> 5 votes
# Wolfram Language (Mathematica), 17 bytes

```
Round[2#/++√5]&

```

Try it online!

# Answer
> 5 votes
# PowerShell, 31 bytes

```
[int]("$args"/1.61803398874989)

```

Try it online!

The ratio of two adjacent numbers in the Fibonacci series rapidly approaches ((1 + sqrt(5)) / 2). So if N is divided by ((1 + sqrt(5)) / 2) and then rounded, the resultant number will be the previous Fibonacci number...

at least according to this article.

-16 thanks mazzy

# Answer
> 5 votes
# Haskell, ~~38~~ 37 bytes

This works for an aribrary size of inputs. We iterate through the Fibonacci sequence until we find some number `x`, that is larger than half the input `n`. This is works because the previous fibonacci number is roughly `0.618*n`. The Fibonacci list `f` was borrowed from R. Martinho Fernandes.

```
g n=[x|x<-f,2*x>=n]!!0
f=0:scanl(+)1f

```

Try it online!

# Answer
> 4 votes
# JavaScript, Node.js, 32 bytes

*-1 thanks to Arnauld*

```
n=>(y=1,f=x=>y-n?f(y,y+=x):x)(0)

```

**Explanation:**

This is a recursive solution, based off one of the two most common recursive fibonacci algorithms, which involves a function `f(x, y) = f(y, x + y)` that stops at some point. With this function, `x` is always a fibonacci number, and `y` is always the fibonacci number after it, so once `y` is the fibonacci number we were given as input, we know `x` is the one before it.

# Answer
> 4 votes
# 05AB1E, 4 bytes

```
ÅF¨θ

```

Try it online or verify some more test cases.

`¨θ` could be a lot of different alternatives, like `Á¤` or ``\`.

**Explanation:**

```
ÅF    # Push a list of Fibonacci numbers lower than or equal to the (implicit) input
  ¨   # Remove the last one (the input)
   θ  # Keep the next last one
      # (after which it is output implicitly as result)

```

# Answer
> 4 votes
# MathGolf, ~~6~~ 4 bytes

```
)φ/i

```

-2 bytes porting *@emanresuA*'s Vyxal answer, which is in turn a port of *@Unmitigated*'s JavaScript answer.

Try it online.

**Original 6 bytes answer:**

```
╒fg<┤Þ

```

Try it online.

`g<` could alternatively also be `á>`: try it online.

**Explanation:**

```
)      # Increase the (implicit) input-integer by 1
 φ/    # Divide it by the golden ratio 1.618033988749895
   i   # Truncate it to an integer
       # (the +1 and truncate act as a round builtin here, which MathGolf lacks)
       # (after which the entire stack is output implicitly as result)

```

```
╒      # Push a list in the range [1, (implicit) input-integer]
 f     # Get the 0-based n'th Fibonacci number for each value in this list
  g    # Filter it by:
   <   #  Where it's smaller than the (implicit) input-integer
    ┤  # Extract the trailing value
     Þ # Discard the list from the stack, keeping just that value
       # (after which the entire stack is output implicitly)

```

# Answer
> 4 votes
### Python 3, ~~50 bytes~~ 48 bytes

```
def f(n,a=0,b=1):
 while b<n:a,b=b,a+b
 return a

```

Try it online!

# Answer
> 4 votes
# Prolog (SWI), 35 bytes

```
1+0.
N+M:-nth1(M,_,_),X is N-M,M+X.

```

Try it online!

-9 bytes thanks to Jo King

Of course, it's shorter to just use floating point:

# Prolog (SWI), 31 bytes

```
N/M:-M is round(2*N/(1+5^0.5)).

```

Try it online!

# Answer
> 3 votes
# Retina 0.8.2, 26 bytes

```
.+
$*
(\2?(\1)|1)+1
$1$2
1

```

Try it online! Link includes test cases. Explanation: Loosely based on @MartinEnder's Retina answer to Am I a Fibonacci Number?.

```
.+
$*

```

Convert to unary.

```
(\2?(\1)|1)+1

```

Match as many Fibonacci numbers as possible. The first iteration only matches the leading `1` while subsequent iterations match iteration of the loop matches the penultimate Fibonacci number (if any), then the previous Fibonacci number, while saving it as the next penultimate Fibonacci number. The match actually sums the Fibonacci sequence, resulting in a sequence one less than the Fibonacci sequence, so a final `1` needs to be matched.

```
$1$2

```

Because the match is summing the sequence, the final capture of the sequence `$1` is actually the Fibonacci number before the one we want, so we need to add on the penultimate matched Fibonacci number `$2`.

```
1

```

Convert to decimal.

# Answer
> 3 votes
# PARI/GP, 16 bytes

```
n->n*2\/(1+5^.5)
```

Attempt This Online!

Port of Unmitigated's JavaScript answer. `a\/b` is a short way to write `round(a/b)`.

PARI/GP's floating point number is 128-bit by default. This gives the correct result until the 184th Fibonacci number (`127127879743834334146972278486287885163`).

# Answer
> 3 votes
# Jelly, 4 bytes

```
‘:Øp

```

Add 1 to the input and integer-divide by the golden ratio.

Try it online!

# Answer
> 3 votes
# Husk, 5 bytes

```
→←xİf

```

Try it online!

Makes use of the built-in list of Fibonacci numbers.

### Explanation

```
→←xİf
   İf  Take the list of Fibonacci numbers
  x    Split it on occurrences of the input
 ←     Get the first sub-list
→      Get the last element of that

```

# Answer
> 3 votes
# Stax, 10 bytes

```
Çâ'Ç,¼)í"─

```

Run and debug it

### Approach

* Start with an infinite Fibonacci generator
* Keep values while they are less than the input, resulting in array e.g. `[1, 1, 2, 3, 5]`.
* Extract last element.

# Answer
> 3 votes
# K (ngn/k), ~~12~~ 11 bytes

```
--2!(1-%5)*

```

Try it online!

Applies @Albert.Lang's approach from this comment.

* `(1-%5)*` calculate 1 minus the square root of 5 (i.e. `-1.2360679774997898`) and multiply it by the (implicit) input
* `-2!` integer divide by 2 (rounding towards 0, e.g. `-8!-7` returns `-1`)
* `-` negate (and implicitly return)

# Answer
> 3 votes
# APL(Dyalog Unicode), 17 bytes SBCS

```
{⌊.5+⍵÷.5×1+5*.5}

```

Try it on APLgolf!

5

# Answer
> 3 votes
# Pip, 10 bytes

```
Ua*DRT5//2
```

Attempt This Online!

# Answer
> 3 votes
# Fig, \\$5\log\_{256}(96)\approx\\$ 4.116 bytes

```
_\mG}

```

Try it online!

No round builtins, so I use the old increment and floor trick.

```
_\mG}
    } # The input number incremented
 \    # Divided by
  mG  # The golden ratio
_     # Floor

```

# Answer
> 3 votes
# Go, 59 bytes

```
import."math"
func f(n float64)float64{return Round(n/Phi)}

```

Attempt This Online!

wow built-in constants

### Calculated version, 72 bytes

```
import."math"
func f(n float64)float64{return Round(2*n/(1+Pow(5,0.5)))}

```

Attempt This Online!

# Answer
> 3 votes
# m68k assembly (GNU), 16 bytes

```
70 00 72 01 d0 81 c1 41 b2 af 00 04 66 f6 4e 75

```

Or in assembly:

```
begin:
    moveq.l #0, %d0;
    moveq.l #1, %d1;
loop:
    add.l %d1, %d0;
    exg.l %d0, %d1;
    cmp.l 4(%sp), %d1;
    bne loop;
    rts;

```

Works with both the Linux and the SysV calling conventions (parameters on stack, return in %d0, %d0-%d1 are scratch registers).

The c function definition is:

```
unsigned long prev_fibonacci(unsigned long num);

```

All calculations are done in 32 bit mode. 16bit is the same size, only faster.

Code execution takes 22 cycles plus 46 cycles per loop iteration. (On a 68000 w/ a 16bit bus and no waitstates)

# Answer
> 3 votes
# x86-64 machine code, 10 bytes

Expects input in `edx` and outputs to `eax`.

```
b8 dd bc 1b cf f7 f0 d1 e8 c3

```

Try it online!

## Explanation

Disassembly:

```
b8 dd bc 1b cf          mov    eax,0xcf1bbcdd
f7 f0                   div    eax
d1 e8                   shr    eax,1
c3                      ret

```

The function approximates \\$\operatorname{round}(\frac{n}{\phi})=\lfloor\frac{n+\frac{\phi}{2}}{\phi}\rfloor=\lfloor\frac{1}{2}\cdot\frac{2^{32}n+2^{31}\phi}{2^{31}\phi}\rfloor\\$, where \\$\phi=\frac{1+\sqrt{5}}{2}\\$. \\$2^{31}\phi\approx3474701533\\$, which fits nicely into a 32-bit integer as `0xcf1bbcdd`. Since `div r32` works on `edx:eax`, `n` can be loaded into `edx` and `0xcf1bbcdd` can be loaded into `eax` to create the numerator of the fraction, while also having `eax` as the denominator of the fraction after `div eax`. Afterwards, all that is left is to divide by two, which is handled by `shr eax, 1`.

# Answer
> 2 votes
# Vyxal, 6 bytes

```
ÞFḟ‹∆f

```

Try it Online!

# Answer
> 2 votes
# rSNBATWPL, 32 bytes

```
x~for{t=1;x>t;f=b}{b=t;t=f+t}$-1

```

Try It Online!

Port of R answer.

# Answer
> 2 votes
# rSNBATWPL, 31 bytes

```
n~(y=1;x~cond{y!n}{{y=y+x}}$x)$

```

Try It Online!

Port of my JS answer:

> This is a recursive solution, based off one of the two most common recursive fibonacci algorithms, which involves a function `f(x, y) = f(y, x + y)` that stops at some point. With this function, `x` is always a fibonacci number, and `y` is always the fibonacci number after it, so once `y` is the fibonacci number we were given as input, we know `x` is the one before it.

# Answer
> 2 votes
# Husk, 6 bytes

```
i*½←√5

```

Try it online!

Same strategy as my R answer (and also those of Luis Mendo and unmitigated).

(Husk has a fibonacci sequence built-in, but using it here seems to come-out longer at 7 bytes: `S!o←€İf`).

Update: proven wrong by Leo

# Answer
> 2 votes
# Desmos, ~~25~~ 22 bytes

*-3 bytes thanks to @Steffan*

```
pp-p~1
f(n)=round(n/p)

```

Port of some of the other answers.

Try It On Desmos!

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

```
f(a){a=2*a/(1+sqrt(5))+.5;}

```

Port of Unmitigated's JavaScript answer.

Try it online!

# Answer
> 2 votes
# Rattle, 17 bytes

```
|r`=+s[$+~[\gq]]0

```

Try it Online!

# Explanation

```
|             take input
 r`           save input as special arg
   =          set top of stack to 0
    +         increment
     s        save value of 1 to storage
      [...]0  infinite loop

 $            swap top of stack with value in storage
  +~          increment top of stack by value in storage
    [\...]    if the top of the stack is equal to the special arg...
      g       get the value in storage (i.e. the previous Fibonacci value)
       q      quit and print implicitly

```

# Answer
> 2 votes
# K (ngn/k), ~~21~~ 22 bytes

```
{_x%1.618033988749895}

```

Try it online!

Increased 1 byte to round the number.

# Answer
> 2 votes
# BitCycle (-u), 93 bytes

Try it online!

```
    v    / <^ ~+AA/v
1v ~B B vC   v> ^/ <
v ~ ?\BB\v  ?= ~ !
1D~ D ^  +C >~
ADA~^   +  ^   B@

```

The program generates a Fibonacci number, doubles it, and compares it to the input. If it's greater than or equal to the input, it is halved and output, otherwise it's discarded and the next number is generated.

```
          the question mark [input] hits a splitter [\]. one bit is redirected while the rest of the bits move to top B  [input].
1v ~B     top D [2fib(n-1)], which starts with 2, is emptied to right A [2fib(n)] and left A [intermittent].
v ~ ?\B   bottom D [2fib(n-2)] empties to right A.
1D~       right A empties to top D and top B [2fib(n)].
ADA~      left A empties to bottom D [2fib(n-2)].

```

```
v    / <   *'top B' refers to BOTH B's; 'bottom B' refers to BOTH B's*
B B vC     if bottom B [input] isn't empty, it hits a splitter. one bit is redirected to D [intermittent] while the rest of the bits re-enter bottom B.
  BB\v     top B [2fib(n)] hits a splitter. one bit is redirected to top C [2fib(n)] while the rest re-enter top B.
D ^  +C    if bottom B is empty, top B hits another splitter. one bit is redirected to bottom C ["2fib(n) >= input"?].
^   +  ^   D will eventually empty to bottom B.

```

```
   ^ ~+AA/v   *'A' refers to BOTH A's
C   v> ^/ <   if bottom C ["2fib(n) >= input"?] isn't empty, it hits a switch. the bits are redirected to B [terminator]
   ?= ~ !     if bottom C is empty, top C [2fib(n)] hits a switch. the bits are redirected into the question mark, destroying them.
 C >~         if bottom C isn't empty, top C empties to A [fib(n)]
      B@      A hits 2 splitters. one bit is redirected away, and another is redirected into the exclamation mark [output]. the rest of the bits re-enter A.
              B empties into the at-sign, which terminates the program.

```

# Answer
> 2 votes
# Ruby, 29 bytes

```
->n{a=b=1;0while n>a=b+b=a;b}

```

Try it online!

# Answer
> 2 votes
# Raku, 40 bytes

```
sub p(\n,\a=0,\b=1){n==b??a!!p(n,b,a+b)}

```

Try it online!

# Answer
> 2 votes
# Scala, 43 bytes

Try it online!

```
def f(n:Int)=((n*math.sqrt(5)-n+1)/2).toInt

```

# Answer
> 1 votes
# Charcoal, 24 bytes

```
ＮθＦ²⊞υιＷ‹⌈υθ⊞υΣ…⮌υ²Ｉ§υ±²

```

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

```
Ｎθ

```

Input the target.

```
Ｆ²⊞υι

```

Start with `[0, 1]`.

```
Ｗ‹⌈υθ

```

Repeat until the target is reached.

```
⊞υΣ…⮌υ²

```

Generate the next Fibonacci number.

```
Ｉ§υ±²

```

Output the highest one less than the input.

# Answer
> 1 votes
# Haskell, 57 bytes (or 14 bytes)

Complete solution which handles arbitrarily large input:

```
f n=(x!!).flip(-)1.length.fst.span(<n)$x
x=scanl(+)0(1:x)

```

Explanation:

1. Let `x` be a an infinite list of fibonacci numbers ( `x = scanl (+) 0 (1:x)` ).
2. Partition list into a tuple (`[Int], [Int]`), the leftmost portion being all numbers `<` than the input.
3. Take the first portion with `fst`.
4. Subtract 1 from the length of that list.
5. Extract (`!!`) the number with the resultant (`idx--`) index from the infinite list.

Simple solution:

```
round.(/0.618)

```

# Answer
> 1 votes
# Brainfuck, 94 bytes

```
>>>>+<<<+[[-]<[->+>+<<]>>[-<<+>>]>>[->+>+<<]>>[-<<+>>]<<<[->>+<<]>[-<+>]>[-<+<<<->>>>]<<<<]>>

```

Input should be entered into the first address. Output is at the address pointed to when the program terminates.

Might add an explanation later.

# Answer
> 1 votes
## Brev, ~~50~~ 45 bytes

```
(define((p x y)n)(if(= n y)x((p y(+ x y))n)))

```

Example:

```
(map (p 0 1) '(34 13 55 2))
=> (21 8 34 1)

```

# Answer
> 1 votes
# TI-BASIC, 13 bytes

```
round(2Ans(1+√(5))⁻¹,0

```

**Hexdump:**
(Token hex-values found here.)

```
12 32 72 10 31 70 BC 35 11 11 0C 2B 30 | round(2Ans(1+√(5))⁻¹,0

```

Takes input in `Ans` and prints the requested output in the challenge.

**Explanation:**

```
round(2Ans(1+√(5))⁻¹,0           ; full program

           1+√(5)                ; phi * 2
          (      )⁻¹             ; 1 / (phi * 2)
       Ans                       ; Ans / (phi * 2)
      2                          ; Ans / phi
round(              ,0           ; round to nearest integer

```

---

**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.

TI-BASIC only has decimal precision up to 14 decimals for calculations and 10 decimals for equivalence.

Byte count is determined via the following steps:

1. Find the program's size via `MEM`\>`Mem Mgmt/Del…`\>`Prgm…`
2. Subtract the length of the program name
3. Subtract the program header length, which is 9 bytes

# Answer
> 1 votes
# \>\<\>, 17 bytes

```
01\~n;
=?\:@+:{:}

```

Try it online

**Explanation**

Starts at **0,1**.
Calculates the next Fibonacci number until we reach the input.
Prints the second newest.

# Answer
> 1 votes
# , ~~12~~ 14 bytes

```
1.61803<.@%~>:

```

Pretty self-explanatory.

Attempt This Online!

```
1.61803<.@%~>:
            >:  NB. increment input
1.61803         NB. golden ratio
          %~    NB. flip arg order and divide
       <.@      NB. then floor the result

```

I saw `1.618` might be too inaccurate. `-:>:%:5` results in `1.61803`, so I added the extra digits.

# Answer
> 1 votes
# C (gcc), ~~26~~ 24 bytes

-4 thanks to c--.

This uses int and overflows at the 46th fib (first exceeding \\$2^{31}\\$) but

`p(n){n=round(n*2/(1+sqrt(5)));}` breaks at 43 and is longer.

```
p(n){n=n*.618033989+.5;}

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
kG/V

```

Try it online!

#### Explanation

```
      # Implicit input...
  /   # ...divided by...
kG    # ...phi...
   V  # ...then rounded
      # Implicit output

```

---
Tags: code-golf, number, fibonacci
---


title: Output the hours at 90 degrees

text:
# Question
Title: Output the hours at 90 degrees
Today while playing with my kids I noticed that an apparently simple toy in the park hid a challenge.

The wheel has a triangle that points to a number, but also has three circles that point to the numbers every 90 degrees from the first one. So:

**Challenge (really simple)**

Given an integer between 1 and 12 (the one pointed by the triangle) in any acceptable form, output also in any acceptable form and order the three numbers pointed by the circles (the ones every 90 degrees).

**Test cases**

```
In       Out
1        4, 7, 10
2        5, 8, 11
3        6, 9, 12
4        7, 10, 1
5        8, 11, 2
6        9, 12, 3
7        10, 1, 4
8        11, 2, 5
9        12, 3, 6
10       1, 4, 7
11       2, 5, 8
12       3, 6, 9

```

This is , so may the shortest code for every language win!

# Answer
# Python 3, 33 bytes

```
lambda n:{*range(n%3,13,3)}-{n,0}

```

Try it online!

---

# Python 2, 35 bytes

```
lambda n:[(n+c)%12+1for c in 2,5,8]

```

Try it online!
> 16 votes

# Answer
# Jelly, 8 bytes

```
12Rṙ’m3Ḋ

```

A monadic link taking a number and returning a list of numbers.

**Try it online!** or see all cases.

### How?

```
12Rṙ’m3Ḋ - Link: number, n   e.g. 5
12       - literal twelve         12
  R      - range                  [1,2,3,4,5,6,7,8,9,10,11,12]
    ’    - decrement n            4
   ṙ     - rotate left            [5,6,7,8,9,10,11,12,1,2,3,4]
      3  - literal three          3
     m   - modulo slice           [5,8,11,2]
       Ḋ - dequeue                [8,11,2]

```
> 11 votes

# Answer
# Python 2, 35 bytes

```
lambda n:(range(1,13)*2)[n+2:n+9:3]

```

Try it online!
> 8 votes

# Answer
# ,  ~~29~~  28 bytes

*Thanks to @Giuseppe for saving a byte!*

```
function(n)(n+1:3*3-1)%%12+1

```

Try it online!
> 7 votes

# Answer
# MATL, 9 bytes

```
I:I*+12X\

```

**Try it online!**

### Explanation

Consider input `4` as an exmaple.

```
I:     % Push [1 2 3]
       % STACK: [1 2 3]
I      % Push 3
       % STACK: [1 2 3], 3
*      % Multiply, element-wise
       % STACK: [3 6 9]
+      % Add implicit input, element-wise
       % STACK: [7 10 13]
12     % Push 12
X\     % 1-based modulus. Implicit display
       % STACK: [7 10 1]

```
> 7 votes

# Answer
# APL+WIN, 13bytes

```
(⎕⌽⍳12)[3×⍳3]

```

Explanation:

```
⎕ Prompt for screen input of indicated time t

⍳12 Create a vector of integers from 1 to 12

⌽ Rotate the vector by t elements front to back

[3×⍳3] Select 3rd, 6th and 9th elements.

```
> 5 votes

# Answer
# C (gcc), 48 bytes

```
i;f(n){for(i=4;--i;printf("%d ",n%12?:12))n+=3;}

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 29 bytes

Similar to xnor's answer.

```
n=>[2,5,8].map(k=>(n+k)%12+1)

```

### Demo

```
let f =

n=>[2,5,8].map(k=>(n+k)%12+1)

for(n = 1; n <= 12; n++) {
  console.log(n + ' -> ' + f(n));
}
```
> 4 votes

# Answer
# Octave, 25 bytes

```
@(x)[a=1:12 a](3+x:3:9+x)

```

Try it online!

Fairly simple anonymous function.

We first create an array of `[1:12 1:12]` \- so two copies of the full number set. Then we index in to select the values of `x+3, x+6, x+9`, where `x` is the number input.

Octave is 1-indexed, so we can simply select the array elements based on the input (although to be honest 0-indexed would use the same number of bytes here).

This seems to use a method that is unique to the other answers in that by having two copies of the array, we don't have to wrap the indices using modulo.
> 4 votes

# Answer
# Befunge-93, ~~20~~ ~~19~~ 18 bytes

```
852<_@#:.+1%+66+&p

```

Try it online!

**Explanation**

```
852                   Push 8, 5 and 2 onto the stack - the offsets we're going to add.
   <                  Reverse direction, and start the main loop.
852                   Push 2, 5, and 8 onto the stack, but we don't actually want these.
                 p    So we use a "put" operation to drop the top three values.
                &     Read the hour from stdin.
               +      Add it to the topmost offset.
         +1%+66       Mod 12 and add 1 to get it in the range 1 to 12.
        .             Then output the result to stdout.
    _@#:              Exit if the next offset is zero (i.e. nothing more on the stack).
   <                  Otherwise start the main loop again.

```

This relies on behaviour specific to the reference interpreter: on end-of-file, the `&` operator returns the last value that was read. That's why we can safely re-read the hour from stdin on each iteration of the loop.
> 3 votes

# Answer
# APL (Dyalog), 12 bytes

```
1+12|2 5 8∘+

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
ƵžS+12%>

```

At the time of writing this, this submission has the lowest score submitted. Technically I am winning!

Try it online!

# How?

```
ƵžS                   # Push the list [2, 5, 8]
   +                  # Add the input to each number
    12%               # Mod each result by 12
       >              # Increment each
                      # And print the ending list implicitly!

```

See this tip of Kevin to know why `Ƶž` is 258!
> 3 votes

# Answer
# SOGL V0.12, 9 bytes

```
3{3+:6«‰P

```

Try it Here!
> 2 votes

# Answer
# Clean, 44 bytes

```
import StdEnv
@n=[(n+i)rem 12+1\\i<-[2,5,8]]

```

Try it online!
> 2 votes

# Answer
# C# (.NET Core), 42 bytes

```
h=>new[]{(2+h)%12+1,(5+h)%12+1,(8+h)%12+1}

```

Try it online!

Essentially just a port of many of the other answers to C#.
> 2 votes

# Answer
# Japt, 11 bytes

```
3ÆU±3 uC ªC

```

Try it

---

## Explanation

Implicit input of integer `U`. Generate a 3 element array () and, for each element, increment `U` by 3 (`U±3`), modulo by 12 (`uC`) and, because `12%12=0`, return the result OR 12 (`ªC`).
> 2 votes

# Answer
# K (oK), 11 bytes

**Solution:**

```
1+12!2 5 8+

```

Try it online!

**Examples:**

```
1+12!2 5 8+1
4 7 10
1+12!2 5 8+2
5 8 11
1+12!2 5 8+3
6 9 12
1+12!2 5 8+4
7 10 1

```

**Explanation:**

This was the first solution that came to mind. Might not be the best or shortest.

```
1+12!2 5 8+ / the solution
     2 5 8+ / add 2, 5 and 8 to the input
  12!       / apply modulo 12 to the results
1+          / add 1

```
> 2 votes

# Answer
# GolfScript, 46 bytes

```
~13,1>:x?:y;0:i;x y 3+12%=x y 6+12%=x y 9+12%=

```

This is the first time I'm doing code golf, so with my lack of experience I've probably not found the best solution, but I need to start somewhere, right?

Try it online or try all cases
> 2 votes

# Answer
# Brain-Flak, 84 bytes

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

```

Try it online!

At least I beat Doorknob's face solution...

Explanation:

```
LOOP 3 TIMES: (()()()){({}<

  n += 2:
   (()(){})
  push 12:
   (((()()()){}){}<>)
  n mod 12 + 1; pushing to both stacks:
   {(({})){({}[()])<>}{}}<>(([{}]{})<>)

END LOOP: >[()])}<>

```
> 2 votes

# Answer
# Pyth, 12 bytes

```
%R12+LQ*R3S3

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica) 20 bytes

```
Mod[#+{3,6,9},12,1]&

```

The normal modulus operation, threaded over a list, offset by 1.

Try it online!
> 2 votes

# Answer
# Vyxal, 8 bytes

```
⁺ẇf+12%›

```

Try it online! (All test cases)

Port of SunnyMoon's 05AB1E solution

**How it works:**

```
⁺ẇf+12%›
⁺ẇ        The number 258
  f       ...as a list of digits ⟨ 2 | 5 | 8 ⟩
   +      Add the input to each
    12%   Mod-12 each
       ›  Increment each
          (implicit output)

```
> 2 votes

# Answer
# Piet \+ ascii-piet, 62 bytes (46×2=92 codels)

```
TABdDTvVvVnNNFJAQUiIiIIAeEeEuUUMTJBCSBvVvVNMLnNnNfFFVBQIMEiCcc

```

Try Piet online!
> 2 votes

# Answer
# Piet \+ ascii-piet, 45 bytes (5×18=90 codels)

```
tAaaqreeumccsqqqijlVa rbiqaaueljnvea?_ t?B tt

```

Try Piet online!

My looping template is getting weirder and weirder... :P

```
inN 4    [n 4]; force toggle CC at the exit of 4 region
Loop:
  dup CC+    [n flag] switch CC on 3rd iteration so it will exit after the loop
  2 1 roll   [flag n]
  2 +        [flag n+2]
  3 dup dup * + %  [flag (n+2)%12]
  1 + d outN [flag next_n] compute and print the next number
  1 outC     [flag next_n] print the separator (ASCII 1)
  2 1 roll   [next_n flag]
  2 /        [next_n flag/2] divide flag by 2; flag becomes odd after two loops

```
> 2 votes

# Answer
# Thunno 2, 8 bytes

```
ṇɗd+12%⁺

```

Try it online!

#### Explanation

```
ṇɗd+12%⁺  # Implicit input
ṇɗ        # Push compressed integer 258
  d+      # Add [2,5,8] to input
    12%   # Mod each by 12
       ⁺  # Increment each
          # Implicit output

```
> 2 votes

# Answer
# Nekomata, 9 bytes

```
12Rᶠ{-Z3¦

```

Attempt This Online!

```
12Rᶠ{-Z3¦
12R         [1,2,...,12]
   ᶠ{       Filter by
     -          Subtract the input
      Z         Check if the result is non-zero
       3¦       Check if the result is divisible by 3

```

---

# Nekomata, 10 bytes

```
258¢D+12%→

```

Attempt This Online!

```
258¢D+12%→
258¢D       Decimal digits of 258
     +      Add
      12%   Modulo 12
         →  Increment

```
> 2 votes

# Answer
# Pushy, 12 bytes

```
258s{K+12%h_

```

**Try it online!**

```
258            \ Push 258
   s           \ Split into digits, yielding [2, 5, 8]
    {K+        \ Add input to each
       12%     \ Modulo each by 12
          h    \ Increment each
           _   \ Print (space separated)

```

## 12 bytes

An alternative for the same byte count:

```
12R{:{;$...#

```

**Try it online!**

```
12R            \ Push range(1, 12), inclusive
   {: ;        \ Input times do:
     {         \   Rotate left
       $       \ While there are items on stack:
        ...    \   Pop the top three
           #   \   Print top item

```
> 1 votes

# Answer
# Haskell, 29 bytes

*-2 bytes thanks to Laikoni.*

```
f n=[mod(n+i)12+1|i<-[2,5,8]]

```

Try it online!

Not very original, no...
> 1 votes

# Answer
# Tcl, 45 bytes

```
proc R i {lmap c {2 5 8} {expr ($i+$c)%12+1}}

```

Try it online!

---

Different approach using the command line arguments:

# Tcl, 39 bytes

```
time {puts [expr [incr argv 3]%12+1]} 3

```

Try it online!
> 1 votes

# Answer
# Swift, 30 bytes

```
{n in[2,5,8].map{($0+n)%12+1}}

```

Try it online!

Port of many other answers to Swift
> 1 votes

# Answer
# Wolfram Language (Mathematica) 35 bytes

```
Range@12~RotateLeft~#~Take~{3,9,3}&

```

The above asserts, in infix notation, what can be expressed more clearly as

```
Function[Take[RotateLeft[Range[12],Slot[1]],List[3,9,3]]]

```

`RotateLeft` rotates `Range[12]`, the sequence 1,2,...12, leftward by the input number. `Slot[1]` or `#` holds the input number, n.

For example, with n = 4,

```
Function[RotateLeft[Range[12],4]]]

```

returns the list

```
{5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4}

```

`Take...{3,9,3}` returns every third element in that list from position 3 through position 9, namely

```
{7, 10, 1}

```
> 1 votes

# Answer
# Pyt, ~~12~~ 11 bytes

```
258á←+26*%⁺

```

Explanation:

```
258               Pushes 2,5,8 onto the stack
   á              Converts the stack to an array, and pushes the array onto the now-empty stack
    ←+            Adds input to [2,5,8]
      26*%⁺       Mod 12 plus 1 (the 'plus 1' allows for '12' to be output)

```

Try it online!
> 1 votes

# Answer
# Perl 6, 23 bytes

```
{map ($_+*)%12+1,2,5,8}

```

Try it online!
> 1 votes

# Answer
# PHP, 37+1 bytes

```
while($i++<3)echo(~-$argn+=3)%12+1,_;

```

Run as pipe with `-nR` or try it online.
> 1 votes

# Answer
## face, ~~96~~ 94 bytes

```
(%d
@)\$*,c'$ooiim%*m1*6%+%%%11m!*mn*m~*3!m&!r!&!is!&$pn3!:L+nn1+nn1%nn%+nn1p~>$inw~>~o-!!1?!L

```

This simply adds two, mods by 12, adds one more, and prints. Then it does that two more times.

Commented version:

```
(%d
@)

\$*,c'$ooii     ( store format string in $, ip in *, get stdin/out )
m%*m1*6%+%%%11  ( initialize constants, %=12, 1=1 )
m!*mn*m~*       ( malloc space for a counter, input var, and length )
3!m&!r!&!i      ( read into & )
s!&$pn          ( scan into n )
3!:L            ( start of main loop, executed thrice )
  +nn1+nn1      ( add 2 to n )
  %nn%+nn1      ( mod by 12 and add 1 more )
  p~>$in        ( sprintf n into > )
  w~>~o         ( output to stdout )
  -!!1          ( decrement counter )
?!L             ( conditional jump back to loop start )

```

Try it online! (The trailing newline is required on TIO due to a bug that's been fixed in a newer version of face.)
> 1 votes

# Answer
# Perl 5, 30 bytes

```
sub{map{($_+$_[0])%12+1}2,5,8}

```

Try it online!
> 1 votes

# Answer
# PowerShell, 30 bytes

```
param($a)2,5,8|%{($_+$a)%12+1}

```

Try it online!

Port of the other answers (e.g., xnor's Python 2 answer). Ho-hum.
> 1 votes

# Answer
# Octave, 23 bytes

```
@(x)mod(x+[2 5 8],12)+1

```

Try it online!

Takes the same approach as most others; and it is golfier than Tom Carpenter's somewhat more unique solution.
> 1 votes

# Answer
# Java 8, ~~46~~ 45 bytes

```
n->new int[]{1-~-~n%12,(5+n)%12+1,(8+n)%12+1}

```

-1 byte thanks to *@ceilingcat*.

Try it online.
> 1 votes

# Answer
# Forth (gforth), 39 bytes

Input is taken from the stack and output is placed on the stack

```
: a 2 + 12 mod 1+ ; : f a dup a dup a ;

```

Try it online!

### Explanation

```
 : a 2 + 12 mod 1+ ; \ helper word to handle adding the hours
    2 +              \ Add 2 to the input
    12 mod           \ get the result modulo 12
    1+               \ add 1

 : f a dup a dup a ; \ word that calculates and outputs the result
    a dup            \ add 3 hours to the input and then duplicate the result
    a dup            \ add 3 hours to the duplicate then duplicate the result
    a                \ add 3 hours to the duplicate

```
> 1 votes

# Answer
# Perl 5 `-a`, 27 bytes

```
say+($_+"@F")%12+1for 2,5,8

```

Try it online!
> 1 votes

# Answer
# Husk, 8 bytes

```
tĊ3ṙḣ12←

```

Try it online!
> 1 votes

# Answer
# x86-16 machine code, 12 bytes

```
00000000: b903 0004 02d4 0c40 aae2 f8c3              ...........

```

Listing

```
B9 0003     MOV  CX, 3          ; loop counter CX = 3
        CLOOP:
04 02       ADD  AL, 2          ; AL = AL + 2
D4 0C       AAM  12             ; AL = AL % 12
40          INC  AX             ; AL = AL + 1
AA          STOSB               ; [DI++] = AL
E2 F8       LOOP CLOOP          ; if --CX > 0 goto CLOOP
C3          RET                 ; return to caller

```

Callable function, input in `AL`, output to buffer at `[DI]`.
> 1 votes

# Answer
# Windows Batch, ~~137 125 111~~ 68 bytes

```
@set/ab=(%1+2)%%12+1,c=(%1+5)%%12+1,d=(%1+8)%%12+1
@echo %b% %c% %d%

```

Port of the `add value to input and mod 12 + 1`
> 0 votes

# Answer
# Ruby, 29 bytes

```
->n{3.times{p 12+(n+=3)%-12}}

```
> 0 votes

# Answer
# , 24 bytes

```
{&((,])}.i.13)@+&(2 5 8)

```

Try it online!
> 0 votes

# Answer
# Stax, 8 bytes

```
äÆL6C╪Θ♪

```

Run and debug it

### Approach

```
3 times:
    add 2
    mod 12
    add 1
    print current value

```
> 0 votes

# Answer
# Excel + Google Sheets Polyglot, 21 Bytes

An anonymous worksheet function that takes input from cell `A1` and returns a 1x3 spilled array beginning at the calling cell.

```
=MOD(A1+{2,5,8},12)+1

```
> 0 votes

---
Tags: code-golf, integer, clock
---


title: Read a password: on mobile!

text:
# Question
Title: Read a password: on mobile!
Thanks to MD XF's recent challenge, we can now read passwords in many different languages! The problem is, now we need to port our applications to mobile devices, and they do password entry a little differently.

# Challenge

* Read a string from the keyboard.
* Each time a character`k` is entered, display it for a short time interval.
* After the time interval has passed OR the user has entered another character, replace `k` with some character `c`.

# Rules

* `c` must be constant; it must be the same character.
* `c` can be any visible character (i.e. it cannot be a newline, space, tab, or unprintable).
* `c` can't be based on any inputted `k`; `c` must be defined/constant before the first `k` is read.
* `c` must be the same every time the program is run.
* `c` can be one of the values given as `k` if by accident, as long as all other rules are followed.
* You must print `k` in realtime. As soon as the user enters a new `k`, you must display it immediately.
* `k` should be visible to the end user before being changed to `c`; the time interval shall not be less than 0.5 seconds.
* `k` should be replaced by `c` within a reasonable time; the time interval shall not exceed 5 seconds.
* As soon as a new character is entered, whether or not the time interval has expired, you should replace `k` with `c` and use the entered key as the new `k` immediately.
* It is acceptable to clear and redraw the screen each time you need to change a character.
* You may use any reasonable methods of input and output as long as all other rules are followed.
* You may assume that the number of characters inputted is never longer than the terminal/graphical window width.
* If using a terminal, your program should terminate after a newline is entered or EOF is reached.
* Your program should function as outlined here on both mobile and other environments.
* Your program may assume that the input will only contain printable characters (letters, numbers, symbols) and possibly a terminating newline (no backspace, arrow keys, delete, etc).
* Your program may terminate when Ctrl+C is pressed.
* You may terminate your program by closing a window, if your program launches one.

# Scoring

This is , so the shortest answer in each language wins!

# Example

Here is an example of what it should look like. Note this is recorded on a mobile platform, but should also work on a desktop platform.

# Answer
> 4 votes
# HTML + JavaScript, 20+105 = 125 bytes

```
<input id=I oninput=v=I.value;s='*'.repeat(l=v.length-1);I.value=s+v[l];clearTimeout(I.t);I.t=setTimeout(`I.value=s+'*'`,1e3)

```

The delay between the entry of `k` and the letter becoming `*` is one second.

## JavaScript `oninput`, Formatted

```
v=I.value;
s='*'.repeat(l=v.length-1);
I.value=s+v[l];
clearTimeout(I.t);
I.t=setTimeout(`I.value=s+'*'`,1e3)

```

## Test Snippet

Added the ending bracket (`>`) for better compatibility.

```
<input id=I oninput=v=I.value;s='*'.repeat(l=v.length-1);I.value=s+v[l];clearTimeout(I.t);I.t=setTimeout(`I.value=s+'*'`,1e3)>
```

# Answer
> 3 votes
# Python 3, 186 224 bytes

Works only in windows.

```
import os,time,msvcrt as m
i=s=x=0;t=time.clock
def v():os.system("cls")
v()
while 1:
 if m.kbhit():
  k=str(m.getch())
  if"\\r"in k:break
  i+=1;x=1;v();print("*"*(i-1)+k[2]);s=t()
 if (t()-s>.6and x):x=0;v();print("*"*i)

```

Older version(186 bytes): The sleep was mandatory regardless of the speed at which key was pressed.

```
import os,time,msvcrt
a=k=[];i=0;o=os.system
while 1:
 o("cls")
 if i:print("*"*(i-1)+a[i-1]);time.sleep(.6);o("cls");print("*"*i)
 k=str(msvcrt.getch())
 if"\\r"in k:break
 a+=k[2];i+=1

```

# Answer
> 3 votes
# Python 2, 133 bytes

Based on @officialaimm answer.

```
import time,msvcrt as m
k=T=0
s=p='\r'
while'\r'!=k:
 t=time.time();print s,
 if m.kbhit():k=m.getch();s=p+k;T=t;p+='*'
 if t-T>1:s=p

```

# Answer
> 0 votes
# HTML + JavaScript, 115 bytes

```
<input id=I oninput="setTimeout(g=>g==I.value?I.value=0+g.slice(0,-1):0,1e3,I.value=I.value.replace(/.(?=.)/g,0))">
```

---
Tags: code-golf, string
---


title: Find the perfect square!

text:
# Question
Title: Find the perfect square!
Your task is to turn a square root like this:

```
√12

```

into a form like this:

```
2√3

```

For our purpose, we only need to output the left number here:

```
2

```

## Test cases

```
4  -> 2
9  -> 3
12 -> 2
13 -> 1
108-> 6

```

## Specifications

* You may assume for the input that \\$n\>0\\$. \\$n\\$ has to be as large as possible.
* If the number is already a perfect square, do this:

```
√4 = 2√1 -> 2

```
* If the number doesn't contain perfect squares, do this:

```
√13 = 1√13 -> 1

```

# Answer
> 6 votes
# Japt `-mx`,  ~~4~~  3 bytes

*Crossed out &nbsp4;  is no longer 4 :)*

```
²vN

```

My first Japt answer. :)
Port of my first 5-byter 05AB1E answer, but with smart use of Japt's flags for the range and sum.

-1 byte thanks to *@Shaggy* thanks to the shortcuts list: `p)`/`p␠` to `²`

Try it online.

**Explanation:**

```
-m       # Convert the (implicit) input-integer to a ranged list [0, input)
  ²      # Square each value in the list, and implicitly close the function
   vN    # Check which values are divisible by the input (1 if truthy; 0 if falsey)
     -x  # After which the sum is calculated of the resulting list
         # (before the result is output implicitly)

```

# Answer
> 11 votes
# 05AB1E, ~~9~~ ~~6~~ 5 bytes

```
LnIÖO

```

Try it online or verify all test cases.

**Previous ~~9~~ 6 bytes approach:**

```
LR.ΔnÖ

```

-3 bytes thanks to *@ovs*.

Try it online or verify all test cases.

**Explanation:**

```
L       # Push a list in the range [1, (implicit) input]
 n      # Take the square of each value in the list
  IÖ    # Check which squares are divisible by the input (1 if truthy; 0 if falsey)
    O   # And sum those checks
        # (after which this sum is output implicitly as result)

L       # Push a list in the range [1, (implicit) input]
 R      # Reverse it to [input, 1]
  .Δ    # Find the first value in this list which is truthy for:
    n   #  Square the current value
     Ö  #  Check if the (implicit) input is evenly divisible by this square
        # (after which the found value is output implicitly as result)

```

# Answer
> 8 votes
# Jelly, 5 bytes

```
Ḷ²%ċ0

```

Uses the formula from the OEIS: the number of solutions to $$x^2 \equiv 0 \ (\mathrm{mod} \ n)$$ Explanation:

* implicit input
* range `0..n-1`,
* square each
* modulo input (I got this part to work via trial and error)
* count zeroes
* implicit print

Try it online!

# Answer
> 7 votes
# Brachylog, 8 6 5 bytes

*-1 thanks to Unrelated String*

```
f↔∋√ℕ

```

Try it online!

### How it works

```
f↔∋√ℕ
    ℕ output is a natural number (≥0) that is
   √  the root of … (Brachylog gives the negative root first)
  ∋   an element …
f↔    in the reverse factors list (so search starts with bigger values)

```

## Alternative version with prime factors, 10 bytes

```
{ḋp⊇~j×}ᵘ⌉

```

Try it online! or verify all test cases.

### How it works

```
{ḋp⊇~j×}ᵘ⌉
         ⌉  take the maximum of …
{      }ᵘ   all unique …
      ×       multiplications of …   10
    ~j        halves of …            [2,5]
   ⊇          ordered subsets from … [2,5,2,5]
  p           the permutations of …  [2,5,2,5,3]
 ḋ            the prime factors      [2,2,3,5,5]

```

# Answer
> 6 votes
# JavaScript (ES6), 27 bytes

```
f=(n,k=n)=>n/k%k?f(n,k-1):k

```

Try it online!

### How?

We recursively look for the greatest \\$k\le n\\$ such that \\$\dfrac{n}{k}\equiv 0\pmod k\\$, which is guaranteed to be satisfied for \\$k=1\\$ in the worst case.

This is a more golf-friendly way of testing \\$\dfrac{n}{k^2}\equiv 0\pmod 1\\$.

# Answer
> 6 votes
# Jelly, 6 bytes

```
ÆE:2ÆẸ

```

A monadic Link accepting a positive integer which yields a positive integer.

**Try it online!** Or see the first 100.

### How?

```
ÆE:2ÆẸ - Link: integer, X          e.g. 9587193
ÆE     - factorisation vector (X)       [0,1,0,4,3] (since 2°×3¹×5°×7⁴×11³=9587193)
  :2   - integer divide by two          [0,0,0,2,1]
    ÆẸ - evaluate factorisation vector  539         (since 2°×3°×5°×7²×11¹=539)

```

# Answer
> 6 votes
# Gaia, 5 bytes

(this was produced by trying a bunch of languages from https://github.com/ETHproductions/golfing-langs until I found one that had the most useful built-ins for this problem)

```
dụ⁇)u

```

Explanation:

```
d     divisors
 ụ⁇   keep only squares
   )  take last
    u square root

```

Try it online! (example stolen from the Jelly answer)

# Answer
> 5 votes
# Python 2, 37 bytes

```
n=i=input()
while n%i**2:i-=1
print i

```

Try it online!

**38 bytes**

```
lambda n:sum(x*x%n<1for x in range(n))

```

Try it online!

Based on the solution of my pronoun is monicareinstate, counting the number of solutions to \\$x^2 \equiv 0 \ (\mathbb{mod}\ n)\\$ for \\$x\\$ from \\$0\\$ to \\$n-1\\$.

# Answer
> 5 votes
# CP-1610 machine code,  ~~20~~  17 DECLEs1 ≈ 22 bytes

*As per the exception described in this meta answer, the exact score is **21.25 bytes** (170 bits)*

A routine expecting the input number in **R0** and returning the result in **R3**.

```
**1D2** |         CLRR    R2
**1C9** |         CLRR    R1
**0D1** | @@loop  ADDR    R2,     R1
**00A** |         INCR    R2
**084** |         MOVR    R0,     R4
**10C** | @@sub   SUBR    R1,     R4
**10C** |         SUBR    R1,     R4
**114** |         SUBR    R2,     R4
**22E 004** |         BGT     @@sub
**20C 001** |         BNEQ    @@next
**093** |         MOVR    R2,     R3
**141** | @@next  CMPR    R0,     R1
**226 00D** |         BLE     @@loop
**0AF** |         JR      R5

```

### How?

The CP-1610 has no multiplication, no division, no modulo. We want to implement an algorithm that relies on additions and subtractions exclusively.

We start with \\$k=0\\$. At each iteration, we update \\$j\\$ in such a way that:

$$j = \frac{k(k-1)}{2}$$

The good thing about this formula is that it's very easy to compute iteratively: we just need to add \\$k\\$ to \\$j\\$ and increment \\$k\\$ afterwards.

In order to test whether \\$n\\$ is divisible by \\$k^2\\$, we initialize a variable \\$x\\$ to \\$n\\$ and subtract \\$k^2\\$ until \\$x\le 0\\$.

We do not explicitly store \\$k^2\\$, but it can be easily obtained with:

$$2j+k=k(k-1)+k=k^2$$

Each time we end up with \\$x=0\\$, we update the final answer to \\$k\\$.

We stop when \\$j\\$ is greater than \\$n\\$.

Here is a link to an implementation of the algorithm in low-level JS.

### Full commented test code

```
        ROMW    10                ; use 10-bit ROM width
        ORG     $4800             ; map this program at $4800

PNUM    QEQU    $18C5             ; EXEC routine: print a number
MULT    QEQU    $1DDC             ; EXEC routine: signed multiplication

        ;; ------------------------------------------------------------- ;;
        ;;  main code                                                    ;;
        ;; ------------------------------------------------------------- ;;
main    PROC

        SDBD                      ; set up an interrupt service routine
        MVII    #isr,   R0        ; to do some minimal STIC initialization
        MVO     R0,     $100
        SWAP    R0
        MVO     R0,     $101

        EIS                       ; enable interrupts

        MVII    #$200,  R3        ; R3 = backtab pointer
        SDBD                      ; R4 = pointer to test cases
        MVII    #@@tc,  R4

@@loop  MVI@    R4,     R0        ; R0 = next test case
        TSTR    R0                ; stop if it's 0
        BEQ     @@done

        PSHR    R4                ; save R4
        PSHR    R3                ; save R3
        CALL    pSquare           ; invoke our routine
        MOVR    R3,     R0        ; copy the result into R0
        PULR    R3                ; restore R3
        CALL    print             ; print the result
        PULR    R4                ; restore R4
        B       @@loop            ; go on with the next test case

@@done  DECR    R7                ; done: loop forever

        ;; test cases
@@tc    DECLE   4, 9, 12, 13, 108, 300, 800, 900
        DECLE   0

        ENDP

        ;; ------------------------------------------------------------- ;;
        ;;  prints the result of a test case                             ;;
        ;; ------------------------------------------------------------- ;;
print   PROC

        PSHR    R5                ; save the return address on the stack

        MVII    #4,     R1        ; R1 = number of digits
        MOVR    R3,     R4        ; R4 = backtab pointer
        ADDI    #5,     R3        ; advance by 5 characters for the next one
        PSHR    R3                ; save R3
        CLRR    R3                ; R3 = attributes (black)
        CALL    PNUM              ; invoke the EXEC routine
        PULR    R3                ; restore R3

        PULR    R7                ; return

        ENDP

        ;; ------------------------------------------------------------- ;;
        ;;  ISR                                                          ;;
        ;; ------------------------------------------------------------- ;;
isr     PROC

        MVO     R0,     $0020     ; enable display
        MVI     $0021,  R0        ; color-stack mode

        CLRR    R0
        MVO     R0,     $0030     ; no horizontal delay
        MVO     R0,     $0031     ; no vertical delay
        MVO     R0,     $0032     ; no border extension
        MVII    #$D,    R0
        MVO     R0,     $0028     ; light-blue background
        MVO     R0,     $002C     ; light-blue border
        MVO     R0,     $002C     ; light-blue border

        JR      R5                ; return from ISR

        ENDP

        ;; ------------------------------------------------------------- ;;
        ;;  our routine                                                  ;;
        ;; ------------------------------------------------------------- ;;
pSquare PROC

        CLRR    R2                ; R2 = k
        CLRR    R1                ; R1 = k(k - 1) / 2

@@loop  ADDR    R2,     R1        ; add R2 to R1
        INCR    R2                ; k++

        MOVR    R0,     R4        ; start with R4 = n

@@sub   SUBR    R1,     R4        ; subtract 2 * (k(k - 1) / 2) = k² - k
        SUBR    R1,     R4        ; from R4
        SUBR    R2,     R4        ; subtract k from R4
        BGT     @@sub             ; until R4 is less than or equal to 0

        BNEQ    @@next            ; did we reach exactly 0? ...

        MOVR    R2,     R3        ; ... yes: update R3

@@next  CMPR    R0,     R1        ; go on while R1 is less than or
        BLE     @@loop            ; equal to R0

        JR      R5                ; return

        ENDP

```

### Output

This is the output for the following test cases:

```
4, 9, 12, 13, 108, 300, 800, 900

```

*screenshot from jzIntv*

---

*1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.*

# Answer
> 5 votes
# Haskell, 30 bytes

```
f n=sum[0^mod(x^2)n|x<-[1..n]]

```

Try it online!

Based on the solution of my pronoun is monicareinstate, counting the number of solutions to \\$x^2 \equiv 0 \ (\mathbb{mod}\ n)\\$ using the range from 1 to n.

# Haskell, 32 bytes

```
f n=until((<1).mod n.(^2))pred n

```

Try it online!

Start with `n` and repeatedly take the `pred`ecessor, `until` it satiafies this condition: when we square it and take the original `n` modulo it, the result is less than 1, that is equal to 0.

# Answer
> 5 votes
# Retina 0.8.2, 26 bytes

```
.+
$*
((^1|11\2)+)\1*$
$#2

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
((^1|11\2)+)

```

Find the largest square number...

```
\1*$

```

... that divides the input...

```
$#2

```

... and output its root.

Bonus 63-byte version that for an input of `√1`, `√2`, `√3`, `√4`, `√5`, `√6`, `√7`, `√8`, `√9`... outputs `1`, `√2`, `√3`, `2`, `√5`, `√6`, `√7`, `2√2`, `3`... etc. (Previous bonus version did not handle `√1` correctly.)

```
\d+
$*
r`(?=^.(\3)+)(.)\3*((1$|11\4)+)
$#4$2$#1
\D1$

^1(\D)
$1

```

Try it online!

# Answer
> 5 votes
# Wolfram Language (Mathematica), 13 bytes

```
√#/._^_:>1&

```

Try it online!

For an integer argument,  (`Sqrt`) returns in the desired `a√b` form (unless the argument was a perfect square).

Then, `/._^_:>1` matches `Power` expressions and replaces them with 1. As `a√b` expands to `Times[a,Power[b,1/2]]`, it becomes `Times[a,1]=a`.

# Answer
> 5 votes
# C (gcc), ~~44~~ ~~33~~ 32 bytes

```
i;f(n){for(i=n;n%(--i*i););n=i;}

```

Try it online!

# Answer
> 4 votes
# , ~~44~~ (crossed-out) ~~36~~ ~~33~~ ~~32~~ 30 bytes

```
((n=scan()):1)[!n%%(n:1)^2][1]

```

Try it online!

Or, a completely-different 25 byte approach based on equivalence to 'number of solutions to x^2==0(mod n)' (as pointed-out by my pronoun is monicareinstate), but that wasn't my own idea and hence seems to me to be cheating: `sum(!(1:(n=scan()))^2%%n)`

# Answer
> 4 votes
# Pari/GP, 15 bytes

```
n->core(n,1)[2]

```

Yes, there is a build-in.

> `core(n,{flag=0})`: unique squarefree integer `d` dividing `n` such that `n/d` is a square. If (optional) flag is non-null, output the two-component row vector `[d,f]`, where `d` is the unique squarefree integer dividing `n` such that `n/d=f^2` is a square.

Try it online!

# Answer
> 4 votes
# Java 10, ~~43~~ 40 bytes

```
n->{for(var c=n++;c/--n%n>0;);return n;}

```

Inspired by *@Arnauld*'s JavaScript answer, so make sure to upvote him!

Try it online.

**Explanation:**

```
n->{                // Method with double as both parameter and return-type
  for(var c=n       //  Create a copy `c` of the input `n`
             ++     //  Then increase `n` by 1
      ;             //  Continue looping as long as:
       c/--n        //   (decrease `n` by 1 first before every iteration with `--n`)
                    //   `c` divided by `n`
            %n>0;)  //   is NOT a multiply of `n` nor 0
  ;return n;}       //  After the loop: return the modified `n` as result

```

# Answer
> 3 votes
# CJam, 15 bytes

```
q~_{_*1$%!},,\;

```

Try it online!

Uses the new method in Kevin Cruijssen's 05AB1E answer.

---

**CJam, 21 bytes**
*This is my old approach to the problem, pre-Kevin Cruijssen's new method which I don't understand*
```
q~mF{[~2/]}%{~#}%{*}*

```

Try it online!

---

*Explanation*
```
q~                     Translate input into a CJam object (allows for easier testing)
  mF                   Factorise with exponents
    {     }%           For each factor
      ~2/              Halve the exponent [and round down]
     [   ]             Capture the base & exponent in an array
            {  }%      For each transformed factor
             ~#        Expand the base and exponent into b^e
                 {*}*  Multiply all the transformed factors together

```

This approach removes all single factors (those that would make up the radical part) whilst halving the paired factors (equivalent to square rooting the integer part).

---

**CJam, 23 bytes**
*A CJam port of Kevin Cruijssen's 05AB1E answer*
```
q~_,(;{_*1$\%0>!},\;)\;

```

Try it online!

# Answer
> 3 votes
# Charcoal, ~~15~~ 12 bytes

Now based on @someone's formula.

```
ＮθＩＬΦθ¬﹪×ιιθ

```

Try it online! Link is to verbose version of code. For each number from `0` to the input, calculates whether its square is divisible by the input, and takes the number of matches.

Alternative version, also 12 bytes:

```
ＮθＩΣＥθ¬﹪×ιιθ

```

Try it online! Link is to verbose version of code. For each number from `0` to the input, calculates whether its square is divisible by the input, and takes the sum of the results.

Alternative version, also 12 bytes:

```
ＮθＩ№Ｅθ﹪×ιιθ⁰

```

Try it online! Link is to verbose version of code. For each number from `0` to the input, calculates the remainder when its square is divisible by the input, and counts the number of zeros.

# Answer
> 2 votes
# Pyth, 9 bytes

```
ef!%Q^T2S

```

Try it online!

```
ef!%Q^T2S
        S   Create range from 1 to (implicit) input
 f          Filter keep from the above, as T, where:
     ^T2      Square T
   %Q         Mod the input with the above
  !           Logical NOT
e           Take the last (largest) element of the filtered list, implicit print

```

# Answer
> 2 votes
# Husk, 9 bytes

-1 byte thanks to Razetime!

```
▲fo¬%1m√Ḋ

```

Try it online! or Try all cases!

### Commented

```
▲          -- the maximum of ...
 fo        -- ... filter on the next two functions composed
   ¬       --     - boolean negate / (== 0)
    %1     --     - modulo 1
      m√   -- ... map square root on ...
        Ḋ  -- ... the list of divisors

```

# Answer
> 2 votes
# perl -MList::Util=max -pl, 34 bytes

```
$n=$_;$_=max grep!($n%$_**2),1..$n

```

Try it online!

This finds the largest square which properly divides the input number. Very inefficient as it tries all numbers from 1 up to the input.

# Answer
> 2 votes
# Ruby, 29 bytes

```
->n,x=n{x-=1while n%x**2>0;x}

```

Try it online!

# Answer
> 2 votes
# , 12 bytes

```
1#.0=[|2^~i.

```

Try it online!

# Answer
> 2 votes
# Arn, ~~12~~ 10 bytes

```
·£æ9Š3nòy├

```

Try it!

# Explained

Unpacked: `+v{!(v^2%}\~`

Uses the formula from the OEIS page: the number of solutions to \\$x^2≡0 (\mod n)\\$

```
              ~     1-range (inclusive) to
                _   variable initialized to STDIN; implied
            +\      folded with addition after
v{                  mapping with block (key of v)
  !                 Boolean NOT
    (               Begin expression
          v
        ^           exponentiated by
          2         two
      %             mod
        _           implied
    )               End expression; implied
}                   End block

```

# Answer
> 1 votes
# Whitespace, 71 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _STDIN_as_integer][T    T   T   _Retrieve_input][S N
S _n=Duplicate_input][N
S S N
_Create_Label_LOOP][S T S S T   N
_Copy_0-based_1st_input][S T    S S T   N
_Copy_0-based_1st_n][S N
S _Duplicate_n][T   S S N
_Multiply][T    S T T   _Modulo][N
T   S S N
_If_0_Jump_to_Label_PRINT_RESULT][S S S T   N
_Push_1][T  S S T   _Subtract][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_RESULT][T   N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Port of *@Sok*'s Pyth answer, so make sure to upvote him! Whitespace doesn't have decimals, so his/her approach is ideal for Whitespace since it doesn't use square-root nor regular division, but only integers.

**Explanation in pseudo-code:**

```
Integer n = STDIN as integer
Integer r = n
Start LOOP:
  Integer s = r * r
  If(n % s == 0):
    Jump to Label PRINT
  r = r - 1
  Go to next iteration of LOOP

Label PRINT:
  Print r as integer to STDOUT
  (implicitly stop the program with an error: no exit defined)

```

# Answer
> 1 votes
# bc, 52 bytes

```
define f(n){for(i=n;i--;){if(!(n%(i*i))){return i}}}

```

Try it online!

# Answer
> 1 votes
# Retina, ~~123~~ 72 bytes

```
.+                        We convert the input into unary
$&*_ $&*_                 and create a copy for factor checking
{` (_+)                   START LOOP: We square the input by multiplying
$& $.1*$1                 its string representation by its length
(?=^.* (_+) (_+))\2+ .+   We check if the square is a factor of the input
$.1                       if so we replace the whole text with the current counter
 (_*)_.*                  Otherwise we decrement the counter by one
 $1                       ---
-- IMPLICIT LOOP END --
-- IMPLICIT OUTPUT --

```

Try it online!

---

This approach is essentially a port of Kevin Cruijssen's 05AB1E answer.
It checks all the numbers from the input downwards until it finds a number whose square divides the original.

---

*-51 bytes*: Many thanks to Neil, whose suggestion helped me to cut off a ridiculous amount of code.

I've also switched from separating with newlines to separating with spaces because `.` is anti-newline.

# Answer
> 1 votes
# MathGolf, 5 bytes

```
╒²k÷Σ

```

Port of my 5-byter 05AB1E answer.

Try it online.

**Explanation:**

```
╒      # Push a list in the range [1, (implicit) input]
       # (could alternatively be `r` for a range [0, input) )
 ²     # Square each value in this list
  k÷   # Check which values are evenly divisible by the input (1 if truthy; 0 if falsey)
    Σ  # And sum those checks
       # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 1 votes
# APL(NARS), 23 chars, 46 bytes

```
{√⍵÷×/(∪a)/⍨2∣≢¨⊂⍨a←π⍵}

```

test:

```
  f←{√⍵÷×/(∪a)/⍨2∣≢¨⊂⍨a←π⍵}
  f 4
2
  f 9
3
  f 12
2
  f 13
1
  f 108
6
  f 2×2×2×2×2×3×3
12

```

comment:

```
{√⍵÷×/(∪a)/⍨2∣≢¨⊂⍨a←π⍵}
                    π⍵  factor argument
                  a←    save that in a list "a" of prime factors
                ⊂⍨      partition "a" in a list of list each element is ugual factors found
            2∣≢¨        to each element of list of list find if number of elements is odd
    ×/(∪a)/⍨           so choice in ∪a the elements appear in list of list as odd and multiple them
  ⍵÷                   divide the argument for the number of factor contained odd times
 √                     make sqrt of that

```

# Answer
> 1 votes
# TI-Basic, 16 bytes

```
sum(not(fPart(seq(I²/Ans,I,1,Ans-1

```

Port of this answer. Takes input in `Ans`. Output is stored in `Ans` and is displayed.

# Answer
> 1 votes
# Thunno 2 `S`, 4 bytes

```
R²$Ḋ

```

Try it online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
R²$Ḋ  # Implicit input
R     # Push [1..input]
 ²    # Square each value
  $   # Push the input again
   Ḋ  # Check for divisibility
      # Sum the resulting list
      # Implicit output

```

# Answer
> 1 votes
# Nekomata, 4 bytes

```
Ď√‼Ṁ

```

Attempt This Online!

```
Ď√‼Ṁ
Ď       Divisors
 √      Integer square root; fails if not a perfect square
  ‼     Remove failed values
   Ṁ    Maximum

```

# Answer
> 0 votes
# Racket, 57 bytes

```
(define(p x[n x])(if(= 0(modulo x(sqr n)))n(p x(- n 1))))

```

Try it online!

---

## Explanation

After receiving input, we create a recursive loop that iterates `n` from the input `x` to 1. At each iteration we check whether the input `x` is divisible by the square of `n`. If it is, we return `n`. Note that this loop will never reach 0 as all divisible by `n` when is \\$n = 1\\$.

$$ p(x, n=x) = \begin{cases} n & x \mod n^2 = 0 \\ p(x, n-1) & otherwise \end{cases} $$

```
(define (perfect-square x [n x])
  (if (zero? (modulo x (sqr n)))
      n
      (perfect-square x (- n 1))))

```

#### What I learnt today

Cool thing I learnt about `define` is the way we can set default arguments to equal previous arguments. If we write `(p 5)`, both `x` and `n` will be set to 5. Saves a ton of bytes. The first draft for this idea was to use a let statement:

```
(define (p x)
  (let loop ([n x])
    ...))

```

## Documentation

*Have wonderful week ahead!*

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


title: Landmine Number V

text:
# Question
Title: Landmine Number V
## Background

You have again x4 been given the task of calculating the number of landmines in a field. But this time, the field is not a number field... it's a field of letters. Our landmine letter operator is sick and requires you to cover for them. They left you the following note:

> Things work a little differently with regards to identifying landmines here. They'll give you pairs of capital letters, I call letter flags, to look out for.
>
> If a pair of letters exist in the landscape, in the given order (not necessarily adjacent), it's a bad sign. If a letter appears between the two given letter flags, which does exist between the two letters in alphabetical order, you've got yourself a landmine.
>
> Count the number of landmines and send 'em to the boss.
>
> Here's an example:
>
> Say you've got AADCRTEBASDVZ, and the letter flags are AE, DE, and FZ Then the landmines would be:
>
> ```
> AE: D in AA[D]CRTE - I highlighted the relevant letters for you with brackets.
> C in AAD[C]RTE
> D again, in A[D]CRTE, because there are two As in the beginning so we have to account for both
> C again, in AD[C]RTE see above DE: has no letters between them, so I know I can skip this one
> FZ: there's no F in the landscape, so I ignore this one
>
> ```
>
> That's a total of 4 landmines. Send off 4, and you're done.
>
> Oh right, I know you've got some fancy automation robo thingy you use for your own thing. I'm an old guy, don't do too well with tech. Maybe you can come up with something for me while I'm gone?
>
> I owe you one.
>
> * R

## Your Task

* Sample Input: The letter landscape, which will only contain letters, and a list of two-letter letter flags. It is given that everything is in capital letters, and that the letter flags are already in alphabetical order.
* Output: Return the landmine score (number of landmines)

**Explained Examples**

```
Input => Output
ABABEBE AE => 8

The landmine letters are:
A[B]ABEBE
ABA[B]EBE
ABABE[B]E
A[B]EBE
ABE[B]E
A[B]ABE
ABA[B]E
A[B]E

```

```
Input => Output
BASCOOSDJE AC AE DE BC => 2

The possible landmine letters are:
AS[C]OOSDJE
ASCOOS[D]JE

```

```
Input => Output
ABCDEFGHIJKLMNOPQRSTUWXYZ HO => 6

The landmine letters are:
H[I]JKLMNO
HI[J]KLMNO
HIJ[K]LMNO
HIJK[L]MNO
HIJKL[M]NO
HIJKLM[N]O

```

```
Input => Output
HSBEBAIWBVWISUDVWJYZGXUEUWJVEEUH AB CD EF GH IJ KL MN OP QR ST UV WZ  => 3

The landmine letters are:
WBVWISUDVWJ[Y]Z
WISUDVWJ[Y]Z
WJ[Y]Z

```

**Test Cases**

```
Input => Output
ABABEBE AE => 8
BASCOOSDJE AC AE DE BC => 2
ABCDEFGHIJKLMNOPQRSTUWXYZ HO => 6
HSBEBAIWBVWISUDVWJYZGXUEUWJVEEUH AB CD EF GH IJ KL MN OP QR ST UV WZ  => 3

IPLEADTHEFIFTH DF AE => 3
XKCDONENINESIXZERO DN AR NO DE XZ  => 3
HTMLISAPROGRAMMINGLANGUAGE LR HJ HM => 7
THEREAREZEROLANDMINESINTHISSENTEN CE => 0
DAQUICKBROWNFOXJUMPSOVERTHELAZYDOGZ HZ => 4
QWERTYUIOPASDFGHJKLZXCVBNMNBVCXZLKJHGFDSAPOIUYTREWQ AC DF GI JL => 6

```

This is , so shortest answer wins.

# Answer
# JavaScript (ES6), 69 bytes

Expects `(set)(string)`.

```
s=>g=([c,...b],o='',[p,,q]=o)=>q?s.has(q+p):c?g(b,o)+(c>o)*g(b,c+o):0

```

Try it online!

### Commented

```
s =>            // s = set of letter flags
g = (           // g is a recursive function taking:
  [ c,          //   c = next character from the landscape
      ...b ],   //   b[] = array of remaining characters
  o = '',       //   o = string of selected letters, in reverse order
  [ p,,         //   p = 1st character of o
        q ] = o //   q = 3rd character of o
) =>            //
q ?             // if q is defined:
  s.has(q + p)  //   increment the result if q + p exists in s
:               // else:
  c ?           //   if c is defined:
    g(b, o) +   //     do a recursive call with o unchanged
    (c > o) *   //     the 2nd call is valid only if c > o
    g(b, c + o) //     do a recursive call with c + o
  :             //   else:
    0           //     stop the recursion

```

---

# Python 3.8, 85 bytes

I was curious to see if a port in Python could compete with user1609012's answer.

Thanks to @tsh who managed to save 4 bytes.

```
f=lambda s,a,o="":o[::-2]in a or s>""==o[2:]and(s[0]>o)*f(q:=s[1:],a,s[0]+o)+f(q,a,o)

```

Try it online!
> 5 votes

# Answer
# Python 3, ~~88~~ 85 bytes

```
lambda l,f:sum(x+z in(x<y<z)*f for x,y,z in combinations(l,3))
from itertools import*

```

Try it online!

-3 bytes thanks to @tsh

## Explanation

Just uses `itertools.combinations` to iterate over all combinations of three characters in the landscape and counts those corresponding to landmines.
> 5 votes

# Answer
Assuming OP made some mistakes in their samples (see comment section):

# Excel (ms365), 168 bytes

Formula in `C1`:

```
=SUM(IFERROR(MAP(B1:B4,LAMBDA(f,LET(x,SEQUENCE(LEN(A1)),s,TOROW(x),l,LEFT(f),r,RIGHT(f),y,TOCOL(TEXTBEFORE(TEXTAFTER(A1,l,x),r,s),2),z,MID(y,s,1),SUM((z>l)*(z<r))))),))

```
> 4 votes

# Answer
# Husk, 7 bytes

```
Σ×¤=…Ṗ3

```

Try it online!

Makes good use of the  range operator, which given a list of characters fills in all the missing characters to leave no gaps in the alphabet. For example:

`…"CF"` =\> `"CDEF"`

`…"ADB"` =\> `"ABCDCB"`

The key here is realising that a three-letters subsequence from the landscape will match the flag IFF the two are equal when  is applied to both of them.

## Explanation

```
Σ×¤=…Ṗ3
     Ṗ3    Get a list of all (ordered) 3-letter subsequences from the landscape
 ×         For each of these subsequences and each flag:
  ¤=…       check if they are equal when … is applied to both (returns 1 or 0)
Σ          Sum all the results

```
> 3 votes

# Answer
# Wolfram Language(Mathematica), 97 bytes

Golfed version. Try it online!

```
g[l_,f_]:=Count[Subsets[Characters@l,{3}],{x_,y_,z_}/;x~Order~y>0&&y~Order~z>0&&f~MemberQ~(x<>z)]

```

Ungolfed version. Try it online!

```
g[l_, f_] := Count[Subsets[Characters@l, {3}], {x_, y_, z_} /; Order[x,y]==1 && Order[y,z]==1 && MemberQ[f, x <> z]]

testCases = {
  {"ABABEBE", {"AE"}, 8},
  {"BASCOOSDJE", {"AC", "AE", "DE", "BC"}, 2},
  {"ABCDEFGHIJKLMNOPQRSTUWXYZ", {"HO"}, 6},
  {"HSBEBAIWBVWISUDVWJYZGXUEUWJVEEUH", {"AB", "CD", "EF", "GH", "IJ", "KL", "MN", "OP", "QR", "ST", "UV", "WZ"}, 3},
  {"IPLEADTHEFIFTH", {"DF", "AE"}, 3},
  {"XKCDONENINESIXZERO", {"DN", "AR", "NO", "DE", "XZ"}, 3},
  {"HTMLISAPROGRAMMINGLANGUAGE", {"LR", "HJ", "HM"}, 7},
  {"THEREAREZEROLANDMINESINTHISSENTEN", {"CE"}, 0},
  {"DAQUICKBROWNFOXJUMPSOVERTHELAZYDOGZ", {"HZ"}, 4},
  {"QWERTYUIOPASDFGHJKLZXCVBNMNBVCXZLKJHGFDSAPOIUYTREWQ", {"AC", "DF", "GI", "JL"}, 6}
};

(actualOutputResults = Table[g @@ testCase[[1 ;; -2]],{testCase, testCases}] ) //Print
If[AllTrue[testCases, g@@(#[[1 ;; -2]]) == #[[3]] &]
    , Print["All tests passed"],
    Print["Some test failed"]]

```
> 2 votes

# Answer
# 05AB1E, ~~22~~ 14 bytes

```
3.ÆεÐêQ×ιнJ}åO

```

-8 bytes by porting *user1609012*'s Python answer, so make sure to upvote that answer as well!

Inputs in the order *landscape, flags*, where *flags* is a list of 2-char strings.

Try it online or verify all test cases.

**Original 22 bytes answer:**

```
ŒʒÀIíÅ¿à}εÇDÁ2£Ÿ¦¨¢O}O

```

Try it online or verify all test cases.

**Explanation:**

```
3.Æ           # Get all triple char-combination of the first (implicit) input-string
   ε          # Map over each triplet of characters:
    Ð         #  Triplicate the current triplet
     ê        #  Sorted-uniquify the top list
      Q       #  Check if it's still the same
       ×      #  Repeat the strings in the remaining triplet that many (0 or 1) times
        ι     #  Uninterleave it into two parts: [a,b,c] → [[a,c],[b]]
         н    #  Pop and keep just the first pair
          J   #  Join them together to a string
   }          # After the map:
    å         # Check for each string whether it's in the second (implicit) input-list
     O        # Sum the truthy values together
              # (which is output implicitly as result)

```

```
Œ             # Get all substrings of the first (implicit) input-string
 ʒ            # Filter these substrings by:
  À           #  Rotate its characters once towards the left
   I          #  Push the second input-list of pairs
    í         #  Reverse each inner pair
     Å¿       #  Check for each reversed pair whether the rotated string ends with it
       à      #  Pop and leave the maximum to check whether any is truthy
 }ε           # After the filter: map over each remaining substring:
   Ç          #  Convert the substring to a list of codepoint-integers
    D         #  Duplicate this list of integers
     Á        #  Rotate the copy once towards the right
      2£      #  Pop and leave just the first two integers
        Ÿ     #  Convert it to a ranged list
         ¦¨   #  Remove the first and last items itself
           ¢  #  Count how many times each inner codepoint-integer occurs
            O #  Sum those counts for the current substring together
  }O          # After the map: sum the list of sums together
              # (which is output implicitly as result)

```
> 2 votes

# Answer
# Charcoal, ~~38~~ 32 bytes

```
ＳθＷＳ⊞υιＩΣ⭆θ⭆…θκ⭆…θμ∧№υ⁺νι∧‹νλ‹λι

```

Try it online! Link is to verbose version of code. Takes the landscape and a list of newline-terminated pairs as input. Explanation: Saved 6 bytes by porting @user1609012's Python answer.

```
ＳθＷＳ⊞υι

```

Input the landscape and the pairs.

```
ＩΣ⭆θ⭆…θκ⭆…θμ∧№υ⁺νι∧‹νλ‹λι

```

For each prefix of each prefix of each prefix of the string, which corresponds to taking combinations of three characters without replacement, count those that correspond to landmines.
> 2 votes

# Answer
# Scala, 153 bytes

Golfed version. Try it online!

```
(l,f)=>{var c=0;for(i<-0 to l.length-1;j<-i+1 to l.length-1;k<-j+1 to l.length-1)if(l(i)<l(j)&&l(j)<l(k)&&f.contains(l(i).toString+l(k).toString))c+=1;c}

```

Ungolfed version. Try it online!

```
import scala.collection.mutable

object Main {
  def g(l: String, f: Array[String]): Int = {
    var count = 0
    for(i <- 0 until l.length) {
      for(j <- i+1 until l.length) {
        for(k <- j+1 until l.length) {
          val x = l(i)
          val y = l(j)
          val z = l(k)
          if(x < y && y < z && f.contains(x.toString + z.toString)) {
            count += 1
          }
        }
      }
    }
    count
  }

  def main(args: Array[String]): Unit = {
    val testLines = List(
      ("ABABEBE", Array("AE"), 8),
      ("BASCOOSDJE", Array("AC", "AE", "DE", "BC"), 2),
      ("ABCDEFGHIJKLMNOPQRSTUWXYZ", Array("HO"), 6),
      ("HSBEBAIWBVWISUDVWJYZGXUEUWJVEEUH", Array("AB", "CD", "EF", "GH", "IJ", "KL", "MN", "OP", "QR", "ST", "UV", "WZ"), 3),
      ("IPLEADTHEFIFTH", Array("DF", "AE"), 3),
      ("XKCDONENINESIXZERO", Array("DN", "AR", "NO", "DE", "XZ"), 3),
      ("HTMLISAPROGRAMMINGLANGUAGE", Array("LR", "HJ", "HM"), 7),
      ("THEREAREZEROLANDMINESINTHISSENTEN", Array("CE"), 0),
      ("DAQUICKBROWNFOXJUMPSOVERTHELAZYDOGZ", Array("HZ"), 4),
      ("QWERTYUIOPASDFGHJKLZXCVBNMNBVCXZLKJHGFDSAPOIUYTREWQ", Array("AC", "DF", "GI", "JL"), 6)
    )

    for ((l, f, expected) <- testLines) {
      assert(g(l, f) == expected)
    }

    println("All tests passed")
  }
}

```
> 1 votes

# Answer
# Retina, 59 bytes

```
~["Lw`"|'|L$`¶(.)(.)
$1.+$2
/.+/_~L$`(.).+(.)
[A-$1$2-Z]¶
.

```

Try it online! Takes the landscape on the first line and the letter pairs on subsequent lines but link is to test suite that splits on spaces for convenience. Explanation:

```
~["Lw`"|'|L$`¶(.)(.)
$1.+$2

```

Get all overlapping substrings of the landscape for each pair of letters.

```
/.+/_~L$`(.).+(.)
[A-$1$2-Z]¶

```

For each substring, remove letters that are not landmines.

```
.

```

Count the landmines.

Example: For the input `IPLEADTHEFIFTH`, `DF`, `AE`, the first stage generates the following command:

```
Lw`D.+F|A.+E

```

The `~` then causes this to be evaluated on the original input producing the list of overlapping substrings `ADTHE`, `DTHEF`, `DTHEFIF`. For each of these, the second stage generates a replacement stage to delete the non-landmines, so for example the last substring `DTHEFIF` produces the following command:

```
[A-DF-Z]

```

This is then executed on the string `DTHEFIF` producing the landmine `E`. The `/.+/` guard on the second stage ensures that it does not execute if there were no substrings.
> 1 votes

# Answer
# , 46 bytes

```
+/@(e.~[:>@,((#~]<{:)\{@;"1(#~]>{.)\.))&(3&u:)

```

Try it online!

* Convert to ascii codes
* For each element in the main input, find all elements to the left that are less, and all to the right that are greater, and create the cartesian product of these. Each of these is a "candidate pair".
    + In J, we do this by zipping the prefix lists (filtered as described above) with the postfixed lists (also filtered).
* Return the number of candidate pairs appearing in the given pairs list
> 1 votes

# Answer
# m68k assembly, 72 bytes

```
20 6f 00 04 48 e7 30 20 70 00 22 6f 00 14 12 18 67 30 14 18 4a 11 67 f2 b2 19
66 f8 76 00 24 49 4a 12 67 08 b4 1a 66 f8 52 83 60 f4 24 49 b2 12 64 0a b4 12
56 cb 00 06 65 02 d0 43 4a 1a 66 ee 60 d2 4c df 04 0c 4e 75

```

Follows the standard Linux/SysV abi.

This loops over all flag pairs individually. For each start flag found, we count the number of end flags coming later in the input. Then we just iterate over all the bytes from the start flag to the end, adding the number of start-end pairs that the byte is contained within to the result.

Or as a demonstration:

```
{A}BABEBE (Find start flag)

{A}BAB[E]B[E] Res = 0, Eflags = 2 (Sum # of end flags (2))

{A}BAB[E]B[E] Res = 4, Eflags = 2 (Add # of end flags to result for every byte between start and end)
   ¯ ¯
{A}BAB(E)B[E] Res = 4, Eflags = 1 (When you hit an end flag, decrement # of eflags)

{A}BAB(E)B[E] Res = 5, Eflags = 0 (Repeat step 3 & 4 until the end)
         ¯
{A}BEBE Res = 5, Eflags = 0 (Start again at step 1 until the end)

```

Here's the code, tested on a TI-89 Titanium:

```
| definition: unsigned short lm5(const char *flag_pairs, const char *input);
.text
.even
.globl lm5
lm5:
    movea.l 4(%sp), %a0;        | Load the flag pair string into %a0
    movem.l %d2-%d3/%a2, -(%sp);
    moveq #0, %d0;              | Zero the minefield counter
per_flag_pair_loop:
    movea.l 20(%sp), %a1;       | Load the beginning of the input string.
                                | This is reloaded at the beginning of handling
                                | every flag pair.
    move.b (%a0)+, %d1; | Load the first flag char.
    beq end;            | If we're at the end of the flag string,
                        | then we're done.
    move.b (%a0)+, %d2; | Load the second flag char.

find_start_flag_loop:       | Loop over all characters looking for the start
                            | flag. If found, compute the number of mines it
                            | adds.
    tst.b (%a1);
    beq per_flag_pair_loop;
    cmp.b (%a1)+, %d1;
    bne find_start_flag_loop;

    moveq #0, %d3;
    movea.l %a1, %a2;

count_end_flag_loop:        | Loop over the input from the flag to the end,
                            | putting the number of end flags in %d3.
    tst.b (%a2);
    beq count_end_flag_loop_end;
    cmp.b (%a2)+, %d2;
    bne count_end_flag_loop;
    addq.l #1, %d3;
    bra count_end_flag_loop;

count_end_flag_loop_end:
    movea.l %a1, %a2;   | We had to overwrite %a2, so reload it before
                        | looping again.

per_start_flag_loop:
    cmp.b (%a2), %d1;
    bhs per_start_flag_is_null;     | The input is too small
    cmp.b (%a2), %d2;
    dbne.w %d3, per_start_flag_is_null; | If the input is the end flag,
                                        | decrement the flag counter
                                        | and jump. Else fallthrough.
    blo per_start_flag_is_null;
    add.w %d3, %d0;             | Increment the result once for
                                | each matching end flag.
per_start_flag_is_null:
    tst.b (%a2)+;               | Null check and _the_ loop's increment.
    bne per_start_flag_loop;
    bra find_start_flag_loop;   | If null, find the next matching start
                                | flag.
end:
    movem.l (%sp)+, %d2-%d3/%a2;
    rts;                        | Output in %d0

```

(TIL that tabs don't work properly here)
> 1 votes

# Answer
# Perl 5, 83 bytes

```
eval"$F[0]=~/$1.*$2(?{\$s+=\$&=~y,$1-$2,,-\$&=~y,$1$2,,})^/"while/ (.)(.)/g;$_=$s|0

```

Try it online!
> 1 votes

# Answer
# Vyxal, 84 bitsv2, 10.5 bytes

```
3ḋ'1⋎⁰cnÞ⇧*;L

```

Try it Online!

Ports user1609012's python answer, so make sure you go upvote that. It's a much simpler answer than what I would have come up with.

## Explained

```
3ḋ'1⋎⁰cnÞ⇧*;L
3ḋ             # Get all combinations without replacement of length 3 from the landscape
  '        ;   # Keep only combinations n where:
   1⋎          #   The combination with the middle letter removed
     ⁰c        #   Is in the list of landmine flags
          *    #   And
       nÞ⇧     #   n is sorted in strict ascending order
            L  # Get the length of the valid combinations

```

Created with the help of Luminespire.
> 0 votes

---
Tags: code-golf
---


# Question
Title: The Math is Right, But the Answer is Wrong - Cops
Robber Thread here

## The Challenge

Choose any numeric\* formula, algorithm, or code challenge. Implement it in such a way that the math is correct, but at least one answer is *wildly*\** wrong due to some defect in how computers/programs operate, e.g. floating point errors, uninitialized/corrupted memory, environment bugs, compiler optimization bugs, library bugs, weird language features, etc...

The domain and range (i.e. inputs and outputs) of your formula must be well-defined.

## Requirements

Your challenge must include the following:

* The formula / algorithm / code challenge
* The source code of your program / function
* A well-defined specification of the domain and range of the program
* A precise description of *how wrong* a particular answer is:
    + Whether it is incorrect deterministically or not- and how often it is incorrect
    + A numeric description of how wrong the returned answer is relative to the expected answer. This could be:
        - in absolute terms (e.g. off by at least 1 million)
        - an order of magnitude (e.g. 1000x larger or smaller)
        - relative to the inputs (e.g. off by more than half the value of the larger of two inputs)
        - some other reasonable measure of error (e.g. correct except for the sign, vector components transposed, rotated by 90 degrees on the complex plane, etc...)
    + A vague estimation of how many outputs of all possible inputs are affected by the error.
    + (if the output is a list, tuple, or matrix) The number of elements affected by the error.
* An environment setup (OS, libraries, language version, runtime, compiler and relevant flags, etc...) which reproduces the error.
    + Include a link to the specific version used for compilers, runtimes, languages, and libraries.
    + You may link to a Docker image or Dockerfile of your environment. Although this is not required, it would be very kind to do so if the environment that causes the numerical error is very specific.
    + Try to keep the set of libraries in use small.

The robbers will be trying to find an incorrect answer and explanation why it fails. Your formula implementation will be considered "safe" after 7 days.

## Example

### Cop Challenge

* Formula: The Pythagorean Theorem, \\$ a^2 + b^2 = c^2 \\$
* Inputs: 2 nonnegative real numbers
* Off by more than either input number
* Affects most inputs
* WSL (Ubuntu 18.04) on Windows 10, Python 3.6.9

```
def badpythag(a, b):
    a2 = (a / 1e200) ** 2
    b2 = (b / 1e200) ** 2
    return math.sqrt(a2 + b2) * 1e200

```

### Cracked Answer

This will fail on many inputs (e.g. 3, 4 =\> 0, but should be 5) due to floating point underflow and return 0. The answer is correct with very large inputs e.g. 3e150 and 4e150, however.

## Rules and Scoring

* Score 1 point if your challenge remains uncracked after 7 days.
* You can submit multiple challenges to the cops thread.
* Incorrect answers do not need to be deterministically wrong as long as they are wrong more than half of the time (a broken clock is right twice a day).
* Abusing undefined behavior is fair game.
* The error should not be hardware dependent. Not everyone has a Raspberry Pi, let alone some obscure model of the x86 with a specific floating point bug.
* GPU code is not allowed. There is too much variance in drivers and graphics cards for this to be a reasonable point of exploitation.
* Caveats on libraries:
    + Errors caused by libraries must be the result of a known and documented flaw. The flaw must have been documented no later than a month before the posting of your cop challenge.
    + You can use old versions of libraries as long as they are publicly available from a reasonably trustworthy source at the time your challenge is posted.
    + Libraries you use must be free for noncommercial personal use and publicly available.
    + Libraries do not need to be open source.
* You can use old language versions (and compilers) as long as they are publicly available from a reasonably trustworthy source at the time the challenge is posted.
* You may exploit compiler and runtime bugs.

---

* By numeric challenge, I mean anything with a domain and range which consists entirely of numbers, tuples/lists of numbers, lists of lists of numbers, vectors, matrices, etc... Complex numbers are fair game. Numbers may use any representation.

\** What is considered *wildly* wrong depends a lot on the scale of the domain and range of the formula/algorithm. What would be wildly wrong for particle physics is a rounding error for walking around the block, while a rounding error for galaxies might be off by a planet or two when trying to find someone's apartment. Yes, this is inherently subjective, but this is why your challenge *must* define a specific numeric definition of exactly what you consider *wrong enough* to count. As a general rule of thumb, to be considered "wildly" wrong, answers should be off by at least an order of magnitude (preferably more), be zero at the wrong time, have the wrong sign, or something else equally nefarious. It should generally be the kind of error that might lead to someone's death if it were to be integrated into medical software rather than something that causes the patient to wake up a little early, while the surgeon is tying up the last few stitches.

# Answer
# Python 3 + sympy, cracked by water\_ghosts

This is a primality checking function. It returns `True` for primes, and `False` for non-primes.

```
from sympy.ntheory.primetest import mr
from sympy.ntheory.generate import primerange

def is_prime(n: int) -> bool:
    if n < 2: return False
    return mr(n, primerange(2, 800))

```

Find a composite number that is falsely declared as prime. There are infinitely many solutions.

You can try it online here. As far as I know, the solution works for any modern version of Python/sympy, no specific environmental setup is required.
> 6 votes

# Answer
# JavaScript (Node.js), Cracked by EasyasPi

```
function max(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw TypeError("This function only accept numbers");
  }
  if (a === b) {
    return a;
  } else if (a > b) {
    return a;
  } else if (a < b) {
    return b;
  } else {
    return Math.max(a, b);
  }
}

function max_ref(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw TypeError("This function only accept numbers");
  }
  return Math.max(a, b);
}

const [a, b] = require('fs').readFileSync(0).toString().split('\n').map(Number);
console.log(max(a, b));
console.log(max_ref(a, b));

```

Try it online!

For a certain inputs: The program exit normally (without exceptions), and the two lines outputted by above program are different.

I know this could be very simple. But I just cannot get a more complex one under this question...
> 1 votes

# Answer
Lua (LuaJit)

Find a number bigger than 0.2 where Expected result == Value. Actually the math is right on paper

```
function Fails(i)
    local max = i * 80
    local a = 0

    while true do
        if a < max then
            a = a + 0.2
        else
            break
        end
    end

    print("Input", i)
    print("Max", max)
    print("Expected Value", max)
    print("Value", a)
end

Fails(...)

```

Try it Lua
> 1 votes

# Answer
# Python 3.10.11

```
import math
def fails(x: float, y: float) -> int:
    return math.lcm(x.as_integer_ratio()[1], y.as_integer_ratio()[1])

```
* Takes two real numbers and outputs the lowest natural number that can be the denominator of the fractions representing both numbers (with an integer numerator). For example, \\$f(0.1,0.32)=50\\$.
* Incorrect very often, and deterministically.
* Off by at least a billion times when it's wrong.
* Infinitely many inputs affected.
* Version 3.10.11 (maybe other versions), should happen on most environments.
> 0 votes

---
Tags: cops-and-robbers
---