text:
Output diagonal positions of me squared
Given a number n, Output an ordered list of 1-based indices falling on either of the diagonals of an n*n square matrix.
Example:
For an input of 3:
The square shall be:
1 2 3
4 5 6
7 8 9

Now we select all the indices represented by \, / or X (# or non-diagonal positions are rejected)
\ # /
# X #
/ # \

The output shall be:
[1,3,5,7,9]

Test cases:
1=>[1]
2=>[1,2,3,4]
3=>[1,3,5,7,9]
4=>[1,4,6,7,10,11,13,16]
5=>[1,5,7,9,13,17,19,21,25]

There will be no accepted answer. I want to know the shortest code for each language.

The question is asking for the (1-indexed) indices of the , / and X characters in the images. Not a bad question per se, but lacks explanation.

If you are willing to provide a brief and clear explanation of what you want, We will probably reopen this, as it is not a bad challenge. As of now, it is just very unclear

I've voted to reopen, though you might also want to move the ascii images out of the examples area to avoid confusion. At first I wasn't sure if I had to produce those as well (but I understand the wanted output is only the list of indices)

@Ruud: And how will do people understand what are the asked positions if they don't see the images?

I'm not saying you shouldn't show them at all, just that you put them (or just two or three of them) with the explanation of the challenge, rather than the example inputs and outputs.

Does the order matter?

@sergiol Is 0-indexing allowed? My previous question stands ^

@Mr.Xcoder: Does the order matter? Yes. Is 0-indexing allowed? No. Because it is how I specified the question in the examples.

FWIW I think having the order be irrelevant might make for more interesting golfs...

Would a dash-separated string be a valid output? e.g. "1-3-5-7-9"

@Arnauld: yes .

@ThePirateBay: If you don't publish the derived challenge, I will publish it myself!

Octave, 28 bytes
@(n)find((I=eye(n))+flip(I))

Anonymous function that inputs a number and outputs a column vector of numbers.
Try it online!

So simple... :)

JavaScript (ES6), 48 bytes
Outputs a dash-separated list of integers as a string.
f=(n,k=n*n)=>--k?f(n,k)+(k%~-n&&k%-~n?'':~k):'1'

Formatted and commented
f = (n, k = n * n) => // given n and starting with k = n²
  --k ?               // decrement k; if it does not equal zero:
    f(n, k) + (       //   return the result of a recursive call followed by:
      k % ~-n &&      //     if both k % (n - 1) and
      k % -~n ?       //             k % (n + 1) are non-zero:
        ''            //       an empty string
      :               //     else:
        ~k            //       -(k + 1) (instantly coerced to a string)
    )                 //   end of iteration
  :                   // else:
    '1'               //   return '1' and stop recursion

Test cases

f=(n,k=n*n)=>--k?f(n,k)+(k%~-n&&k%-~n?'':~k):'1'

;[1,2,3,4,5].forEach(n => console.log(n, '->', f(n)))

Nice workaround, using the signs as separators. Could you use bitwsie & to save a byte?

@Shaggy No, that wouldn't work. For instance: 4%3 and 4%5 have no 1-bit in common, but both are non-zero.

Yup, just tested it with n=5 and spotted that it wouldn't work.

k%~-n&&k%-~n should work. nice trick with the separator!

@Titus Not that it really matters when it comes to golfing but ... yeah, that might be slightly more readable. :-) (updated)

R, 38 35 34  38 bytes
3 bytes saved when I remembered about the existence of the which function...
, 1 byte saved thanks to @Rift
d=diag(n<-scan());which(d|d[n:1,])

+4 bytes for the argument ec=T when called as a full program by source()
Try it online!
Explanation:
n<-scan()            # take input
d=diag(n);           # create an identity matrix (ones on diagonal, zeros elsewhere)
d|d[n:1,]            # coerce d to logical and combine (OR) with a flipped version
which([d|d[n:1,]])   # Find indices for T values in the logical expression above

-1 byte d=diag(n<-scan());which(d|d[n:1,])

When running this as a full program (source) this doesn't print anything. You have to call cat. See this post on meta.

@JarkoDubbeldam Fair enough! I had always worked on the basis that it gives valid output on TIO, never really considered the requirements of being a "full program".

Though I'm not planning on going back and editing all my old answers to fix this!

It is a bit vague, because of the console environment of R and code snippets being the main way of using it. Feel free to share insights on that meta thread I linked. It hasn't received all that much input.

37 bytes as a function

Jelly, 8 bytes
⁼þ`+Ṛ$ẎT

Try it online!
Uses Luis Mendo's algorithm on his MATL answer.

Mhm, I am quite surprised you didn't use ŒD.

@Mr.Xcoder ŒD does something completely different from X of a specific size.

Octave, 41 37 bytes
This works in MATLAB too by the way. No sneaky Octave specific functionality :)
@(x)unique([x:x-1:x^2-1;1:x+1:x*x+1])

Try it online!
Explanation:
Instead of creating a square matrix, and find the two diagonals, I figured I rather calculate the diagonals directly instead. This was 17 bytes shorter! =)
@(x)                                   % Anonymous function that takes 'x' as input
    unique(...                   ...)  % unique gives the unique elements, sorted
           [x:x-1:x^2-1                % The anti-diagonal (is that the correct word?)
                       ;               % New row
                        1:x+1:x*x+1])  % The regular diagonal

This is what it looks like, without unique:
ans =
    6   11   16   21   26   31
    1    8   15   22   29   36

Yes, I should probably have flipped the order of the diagonals to make it more human-friendly.

MATL, 6 bytes
XytP+f

Try it online!
Explanation
Same approach as my Octave answer.
Consider input 3 as an example.
Xy   % Implicit input. Identity matrix of that size
     % STACK: [1 0 0;
               0 1 0;
               0 0 1]
t    % Duplicate
     % STACK: [1 0 0
               0 1 0
               0 0 1],
              [1 0 0
               0 1 0
               0 0 1]
P    % Flip vertically
     % STACK: [1 0 0
               0 1 0
               0 0 1],
              [0 0 1
               0 1 0
               1 0 0]
+    % Add
     % STACK: [1 0 1
               0 2 0
               1 0 1]
f    % Linear indices of nonzero entries. Implicit display
     % STACK:[1; 3; 5; 7; 9]

Linear indexing is column-major, 1-based. For more information see length-12 snippet here.

What is "transpose" supposed to mean?

@EriktheOutgolfer Sorry, my bad. t is duplicate, not transpose. Also, I've added a worked out example

Amazing! It would take me two loops if I want to accomplish this.

@LuisMendo I suspected so, because transposing an identity matrix makes no sense...hmm, I managed to save a byte with your algorithm.

Python 2, 54 53 bytes
lambda n:[i+1for i in range(n*n)if i%-~n<1or i%~-n<1]

Try it online!

Mathematica, 42 bytes
Union@Flatten@Table[{i,#+1-i}+i#-#,{i,#}]&

Try it online!
@KellyLowder golfed it down to..
Mathematica, 37 bytes
##&@@@Table[{i-#,1-i}+i#,{i,#}]⋃{}&

and @alephalpha threw away the table!
Mathematica, 34 bytes
Union@@Range[{1,#},#^2,{#+1,#-1}]&

##&@@@Table[{i-#,1-i}+i#,{i,#}]⋃{}& is 5 bytes shorter

Union@@Range[{1,#},#^2,{#+1,#-1}]&

Octave, 68 54 bytes
Thanks to @Stewie Griffin for saving 14 bytes!
@(x)unique([diag(m=reshape(1:x^2,x,x)),diag(flip(m))])

Try it online!
MATLAB, 68 bytes
x=input('');m=reshape([1:x*x],x,x);unique([diag(m) diag(flipud(m))])

Explanation:
@(x)                               % Anonymous function
m=reshape([1:x*x],x,x);            % Create a vector from 1 to x^2 and
                                   % reshape it into an x*x matrix.
diag(m)                            % Find the values on the diagonal.
diag(flip(m))                      % Flip the matrix upside down and
                                   % find the values on the diagonal.
unique([])                         % Place the values from both diagonals
                                   % into a vector and remove duplicates.

C# (.NET Core), 97 83 bytes
f=>{var s="[";for(int i=0;i<n*n-1;)s+=i%-~n<1|i++%~-n<1?i+",":"";return s+n*n+"]";}

Try it online!
The change here is based on the shift between numbers to find. The two shifts starting at 0 are n-1 and n+1, so if n=5, the numbers for n-1 would be 0,4,8,12,16,20 and for n+1 would be 0,6,12,18,24. Combining these and giving 1-indexing (instead of 0-indexing) gives 1,5,7,9,13,17,19,21,25. The offset from n is achieved using bitwise negation (bitwise complement operation), where ~-n==n-1 and -~n==n+1.
Old Version
f=>{var s="[";for(int i=0;i<n*n-1;i++)s+=(i/n!=i%n&&n-1-i/n!=i%n?"":i+1+",");return s+$"{n*n}]";}

Try it online!
This approach uses the column and row indices for determining if the numbers are on the diagonals. i/n gives the row index, and i%n gives the column index.
Returning Only The Number Array
If constructing only the number array is deemed to count towards the byte cost, then the following could be done, based on Dennis.Verweij's suggestion (using System.Linq; adds an extra 18 bytes):
C# (.NET Core), 66+18=84 bytes
x=>Enumerable.Range(1,x*x).Where(v=>~-v%~-x<1|~-v%-~x<1).ToArray()

Try it online!

you can reduce the code by getting rid of the extra &. The extra & is there only to break the comparison if the first input is false MSDN

in fact you can have 92 bytes by using Linq Try it online!

@Dennis.Verweij Neat, I wasn't sure how much I could shift to the header or footer in TIO. I'll have a play around with mine.

you have to remember to include 18 bytes for the reference to linq (using System.Linq;) which is unfortunate, but how it works :S

Ah, ok. But that isn't necessary for using System;? (I assume wrapping it in a namespace System.Linq isn't valid?)

Proton, 41 bytes
n=>[i+1for i:0..n*n if!(i%-~n)or!(i%~-n)]

Try it online!

MATL, 14 bytes
U:GeGXytPY|*Xz

Try it online!

6 bytes

Wow! Please post it, I'll eventually delete mine

I will post it if you are not going to incorporate it into your answer; but no need to delete yours

C (gcc), 65 58 bytes
-7 bytes thanks to Titus!
f(n,i){for(i=0;i<n*n;i++)i%-~n&&i%~-n||printf("%d ",i+1);}

Try it online!

i%-~n&&i%~-n||printf("%d ",i+1) (-7 bytes)

Javascript, 73 63 bytes
old version
n=>[...Array(y=n*n).keys(),y].filter(x=>(--x/n|0)==x%n||(x/n|0)==n-x%n-1)

Saved 10 bytes thanks to @Shaggy
n=>[...Array(n*n)].map((_,y)=>y+1).filter(x=>!(--x%-~n&&x%~-n))

First time golfing! here's hoping I didn't mess up too badly.

let f=n=>[...Array(n*n)].map((_,y)=>y+1).filter(x=>!(--x%-~n&&x%~-n));
[1,2,3,4,5].forEach(n=>console.log(f(n)))

Welcome to PPCG :) A similar solution to the one I was working on (only mine is 0-indexed). You might be able to save some bytes by using the following in your filter function: !(--x%(n+1)&&x%(n-1)) and by creating your array like so: [...Array(n*n+1).keys()]

@Shaggy Thank you! I'll try to improve the answer with your suggestion as soon as I get home from work!

You're welcome. By the way: "it's a bit shorter than creating a [1...n*n] range with Array(n*n).fill().map((x,i)=>i+1)" - [...Array(n*n)].map((_,y)=>y+1) is a shorter way of doing that, for future reference.

Did a bit more with it and ended up with this for 56 bytes: n=>[...Array(n*n+1).keys()].filter(x=>!(--x%-~n&&x%~-n))

@Shaggy I tried your last version but it would output an extra zero for f(1) and f(2), it works with a [1...n*n] range though so I used the way you showed me in the previous comment. Or maybe I messed up someway?

Octave, 32 bytes
@(n)find((m=abs(--n:-2:-n))==m')

Try it online!

Pyth, 20 18 bytes
(Here is the initial version.)
hMf|<%ThQ1<%TtQ1U*

Test Suite.
Pyth, 18 bytes
hMf>1*%ThQ%T|tQ1U*

Test Suite.

Perl 5, 56 + 1 (-n) = 57 bytes
!(($_+1+$_/$,)%$,&&$_%($,+1))&&say++$_ for 0..($,=$_)**2

Try it online!

Shouldn't  -n be +3?

No.  The assumed command line is perl -e.  The command line for this example would be perl -ne.  That's a difference of +1.

Java (OpenJDK 8), 71 bytes
n->{for(int i=0;i<n*n;i++)if(i%-~n<1||i%~-n<1)System.out.println(i+1);}

Try it online!
Port of scottinet's answer.

Japt, 16 bytes
Can't seem to do better than this but I'm sure it's possible. Had to sacrifice 2 bytes for the unnecessary requirement that we use 1-indexing.
²õ f@´XvUÉ ªXvUÄ

Test it

PHP, 56 54+1 bytes
+1 byte for -R flag
for(;$z**.5<$n=$argn;$z++)$z%-~$n&&$z%~-$n||print~+$z;

prints numbers prepended by dashes. Run as pipe with -nR or try it online.
requires PHP 5.6 or later for ** operator.
Add one byte for older PHP: Replace ;$z**.5<$n=$argn with $z=$argn;$z<$n*$n.

Ruby, 45 bytes
->n{(n*n).times{|i|i%-~n>0&&i%~-n>0||p(i+1)}}

Works internally as zero indexed. checks if i modulo n+1 or n-1 is 0, if so prints i+1.

Husk, 12 bytes
ṁo►L∂Se↔C¹ḣ□

Try it online!
indices are unordered.


text:
Modular multiplicative inverse
Your task is to given two integer numbers, a and b calculate the modular multiplicative inverse of a modulo b, if it exists.
The modular inverse of a modulo b is a number c such that ac ≡ 1 (mod b). This number is unique modulo b for any pair of a and b. It exists only if the greatest common divisor of a and b is 1.
The Wikipedia page for modular multiplicative inverse can be consulted if you require more information about the topic.
Input and Output
Input is given as either two integers or a list of two integers. Your program should output either a single number, the modular multiplicative inverse that is in the interval 0 < c < b, or a value indicating there is no inverse. The value can be anything, except a number in the range (0,b), and may also be an exception. The value should however be the same for cases in which there is no inverse.
0 < a < b can be assumed
Rules

The program should finish at some point, and should solve each test case in less than 60 seconds
Standard loopholes apply

Test cases
Test cases below are given in the format, a, b -> output
1, 2 -> 1
3, 6 -> Does not exist
7, 87 -> 25
25, 87 -> 7
2, 91 -> 46
13, 91 -> Does not exist
19, 1212393831 -> 701912218
31, 73714876143 -> 45180085378
3, 73714876143 -> Does not exist

Scoring
This is code golf, so the shortest code for each language wins.
This and this are similar questions, but both ask for specific situations.

Sandbox

Can our output be empty in case there is no such value?

@Mr.Xcoder Yes, but in that case it would need to be empty for all cases in which there is no such value

It follows from Fermat's Little Theorem that the multiplicative inverse of a, if it exists, can be computed efficiently as a^(phi(b)-1) mod b, where phi is Euler's totient function: phi(p0^k0 * p1^k1 * ...) = (p0-1) * p0^(k0-1) * (p1-1) * p1^(k1-1) * ...  Not saying it leads to shorter code :)

Can we output a optional type?  I'm assuming we can but I just wanted to check.

can I take as input [a,-1,b] ?

@Jenny_mathy Taking additional input is generally disallowed.

@Mr.Xcoder yes but I would beat mathematica's built in which is generally great!

I count six answers that seem to be brute forcing, and unlikely to run all test cases in 60 seconds (some of them give a stack or memory error first).

@ngn : You've conflated Fermat's Little Theorem (FLT) with Euler's improvement to it.  Fermat did not know about the Euler phi function.  Further, FLT and Euler's improvement only apply if gcd(a,b) = 1.  Finally, in the form you have written it, "a^(\phi(b)-1) mod b" is congruent to 1, not a^(-1).  To get a^(-1), use a^(\phi(b)-2) mod b.

@EricTowers Euler's is a consequence. Regarding "gcd(a,b)=1" - I did say "if it [the inverse] exists". Are you sure about phi(b)-2?

@ngn : Hmm...  Seems you got me turned around.  It's a^(b -2) = a^(-1) mod p in Fermat's theorem and a^(phi(b) -1) = a^(-1) mod p in Euler's.

@EricTowers Looks correct now, assuming by "p" you mean "b=p, where p is prime". I admit it would have been more proper, though just as true, to quote Euler's theorem (which is the generalisation to multiple prime factors) instead of Fermat's Little.

60 seconds on which machine?

@totallyhuman Reasonable normal machine

So at least @Mr.Xcoder claims that his brute force solution (in Python) does run in less than 60 seconds on a normal machine - barely. Which is exactly what you'd want to avoid in choosing a non-scoring time limit.

Why limit the algorithm for just positive results and arguments, when during the computation one see values can be negative, the same the result,and that algorithm it is for all integers (negative positive zero)?

Mathematica, 14 bytes
Obligatory Mathematica builtin:
ModularInverse

It's a function that takes two arguments (a and b), and returns the inverse of a mod b if it exists. If not, it returns the error ModularInverse: a is not invertible modulo b..

JavaScript (ES6), 79 73 62 61 bytes
Returns false if the inverse does not exist.
It uses the extended Euclidean algorithm and solves all test cases almost instantly.
f=(a,b,c=!(n=b),d=1)=>a?f(b%a,a,d,c-(b-b%a)/a*d):b<2&&(c+n)%n

Test cases

f=(a,b,c=!(n=b),d=1)=>a?f(b%a,a,d,c-(b-b%a)/a*d):b<2&&(c+n)%n

console.log(f(1, 2)) // -> 1
console.log(f(3, 6)) // -> Does not exist
console.log(f(7, 87)) // -> 25
console.log(f(25, 87)) // -> 7
console.log(f(2, 91)) // -> 46
console.log(f(13, 91)) // -> Does not exist
console.log(f(19, 1212393831)) // -> 701912218
console.log(f(31, 73714876143)) // -> 45180085378
console.log(f(3, 73714876143)) // -> Does not exist

Why is it not possible to write the name of function f, as in                             f(c,a,b=0,d=1,n=a)=>c?f(a%c,c,d,b-(a-a%c)/c*d,n):a<2&&(b+n)%n ?

@RosLup f(x,y) is always parsed as a function call, except if it is explicitly preceded by the function keyword. An anonymous arrow function, on the other hand, is declared as (x,y)=>something and f=(x,y)=>something assigns the function to the f variable.

Python 2, 34 bytes
f=lambda a,b:a==1or-~b*f(-b%a,a)/a

Try it online!
Recursive function that gives True for print f(1,2), which I believe to be acceptable, and errors for invalid inputs.
We are trying to find \$x\$ in \$a\cdot x\equiv 1\pmod{b}\$.
This can be written as \$a\cdot x-1=k\cdot b\$ where \$k\$ is an integer.
Taking \$\mod{a}\$ of this gives \$-1\equiv k\cdot b\pmod{a}\$. Moving the minus gives \$-k\cdot b\equiv1\pmod{a}\$, where we have to solve for \$k\$.
Seeing how it resembles the initial scenario, allow us to recurse to solve for \$k\$ by calling the function with \$f(-b\%a,a)\$ (works because Python gives positive values for modulo with a negative argument).
The program recurses for until \$a\$ becomes 1, which only happens if the original \$a\$ and \$b\$ are coprime to each other (ie there exists a multiplicative inverse), or ends in an error caused by division by 0.
This value of \$k\$ can be substituted in the equation \$a\cdot x-1=k\cdot b\$ to give \$x\$ as \$\frac{k\cdot b+1}{a}\$.

Jelly, 2 bytes
æi

Try it online!
This uses a builtin for modular inverse, and returns 0 for no modular inverse.
Jelly, 7 bytes
R×%⁸’¬T

Try it online!
Outputs empty set (represented as empty string) on no modular inverse. Runs out of memory on TIO for the largest test-cases, but should work given enough memory.
How it Works
R×%⁸’¬T
R        Generate range of b
 ×       Multiply each by a
  %⁸     Mod each by b
    ’    Decrement (Map 1 to 0 and all else to truthy)
     ¬   Logical NOT
      T  Get the index of the truthy element.

If you want to work for larger test-cases, try this (relatively ungolfed) version, which requires much time rather than memory:
Jelly, 9 bytes
×⁴%³’¬ø1#

Try it online!
How it Works
×⁴%³’¬ø1#
        #   Get the first
      ø1      one integer
            which meets:
×⁴            When multiplied by a
  %³          And modulo-d by b
    ’         Decrement
     ¬        Is falsy

Mathematica, 18 bytes
PowerMod[#,-1,#2]&

input

[31, 73714876143]

Japt, 9 8 bytes
Takes the inputs in reverse order. Outputs -1 for no match. Craps out as the bigger integer gets larger.
Ç*V%UÃb1

Test it

Saved 1 byte thanks to ETH pointing out an errant, and very obvious, space.

The test input 73714876143,31 seems to produce an out-of-memory error on Firefox (and to crash Chromium). I don't think this is a valid answer.

@IlmariKaronen: I clearly pointed out that fact in my solution. We can assume infinite memory for the purposes of code golf so the memory issues and crashes do not invalidate this solution.

Unfortunately the memory issues also make it impossible to tell whether your code would actually solve the test cases in 60 seconds as stipulated by the challenge. I suspect it would not, even if there was sufficient memory available to make it not crash, but without a computer that can actually run the program for that long there's no way to tell for sure.

R + numbers, 15 bytes
numbers::modinv

returns NA for those a without inverses mod b.
R-Fiddle to try it!
R, 33 bytes (non-competing)
This will fail on very large b since it actually creates a vector of size 32*b bits.
function(a,b)which((1:b*a)%%b==1)

Try it online!
Returns integer(0) (an empty list) for those a without inverses mod b.

J, 28 bytes
4 :'(1=x+.y)*x y&|@^<:5 p:y'

Try it online!
Uses Euler's theorem. Returns 0 if the inverse does not exist.
Explanation
4 :'(1=x+.y)*x y&|@^<:5 p:y'  Input: a (LHS), b (RHS)
4 :'                       '  Define an explicit dyad - this is to use the special
                              form `m&|@^` to perform modular exponentiation
                          y   Get b
                      5 p:    Euler totient
                    <:        Decrement
             x                Get a
                   ^          Exponentiate
               y&|@             Modulo b
       x+.y                   GCD of a and b
     1=                       Equals 1
            *                 Multiply

Python 2, 51 49 54 53 51 49 bytes
-1 byte thanks to officialaimm
-1 byte thanks to Shaggy

a,b=input()
i=a<2
while(a*i%b-1)*b%a:i+=1
print+i

Try it online!
Prints 0 when there is no solution.

Outputs 0 for a=1 and b=2; from the test cases, it should output 1.

As a recursive algo

As Shaggy pointed out, fails for 2, 1

@Shaggy should work now

This fails to return an answer in 60 seconds (on TIO) for the input 31,73714876143.

This goes into infinite loop for the input 4, 6, since there is no inverse, but b%a != 0. (For inverse to exist, it's not enough that b is not divisible by a, you need them to be coprime.)

Pyth, 10 bytes
3 bytes saved thanks to @Jakube.
xm%*szdQQ1

Try it here!
Returns -1 for no multiplicative inverse.
Code Breakdown
xm%*szdQQ1      Let Q be the first input.
 m      Q       This maps over [0 ... Q) with a variable d.
   *szd         Now d is multiplied by the evaluated second input.
  %    Q        Now the remained modulo Q is retrieved.
x        1      Then, the first index of 1 is retrieved from that mapping.

Pyth, 15 13 bytes
KEhfq1%*QTKSK

Throws an exception in case no multiplicative inverse exists.
Try it here!
Pyth, 15 bytes
Iq1iQKEfq1%*QTK

This adds lots of bytes for handling the case where no such number exists. The program can be shortened significantly if that case would not need to be handled:
fq1%*QTK

Try it here!

2 bytes saved with KExm%*QdKK1

Or 3 bytes if you swap the order of inputs: xm%*szdQQ1

@Jakube Thanks a lot, editing!

How does this work?

@Cowsquack I've added a completely primitive code breakdown but rn I don't have time to include a complete explanation.  Hopefully it is clear enough for now but I'll try to add a more complete explanation soon.

@Mr.Xcoder no rush, I wondered how the algorithm worked, thanks

Python 3 + gmpy, 23 bytes
I don't think it can get any shorter in Python.
gmpy.invert
import gmpy

Try it online! (won't work if you do not have gmpy installed)

Python 3, 49 bytes
lambda a,b:[c for c in range(b)if-~c*a%b==1][0]+1

Try it online!
Python 3, 50 bytes
lambda a,b:[c for c in range(1,b+1)if c*a%b==1][0]

Try it online!
This throws IndexError: list index out of range in case there is no modular multiplicative inverse, as it is allowed by the rules.

This fails to return a result for the input 31,73714876143 in 60 seconds (on TIO).

@IlmariKaronen Seems to finish in 56 seconds on my machine (Macbook Pro '15)

8th, 6 bytes
Code
invmod

Explanation
invmod is a 8th word that calculates the value of the inverse of a, modulo b. It returns null on overflow or other errors.
Usage and test cases
ok> 1 2 invmod .
1
ok> 3 6 invmod .
null
ok> 7 87 invmod .
25
ok> 25 87 invmod .
7
ok> 2 91 invmod .
46
ok> 13 91 invmod .
null
ok> 19 1212393831 invmod .
701912218
ok> 31 73714876143 invmod .
45180085378
ok> 3 73714876143 invmod .
null

Pari/GP, 11 bytes
a->b->1/a%b

Throws an error when there is no inverse.
Try it online!

C (gcc), 48 110 104 bytes
#define f(a,b)g(a,b,!b,1,b)
long g(a,b,c,d,n)long a,b,c,d,n;{a=a?g(b%a,a,d,c-(b-b%a)/a*d):!--b*(c+n)%n;}

Try it online!
This should work with all inputs (that fit within a long) within 60 seconds.
Edit. I'm already abusing the n variable so I might as well assume that gcc puts the first assignment in %rax.

Alas, this gives wrong results even for fairly small inputs due to integer overflow inside the loop. For example, f(3,1000001) returns 717, which is obviously nonsense (the correct answer is 333334). Also, even if this bug was fixed by using a wider integer type, this brute-force approach would certainly time out for some of the larger test cases given in the challenge.

C (gcc), 115 bytes
#define L long long
L g(L a,L b,L c,L d){return a?g(b%a,a,d-b/a*c,c):b-1?0:d;}L f(L a,L b){return(g(a,b,1,0)+b)%b;}

Try it online!
Extended Euclidean algorithm, recursive version
C (gcc), 119 bytes
long long f(a,b,c,d,t,n)long long a,b,c,d,t,n;{for(c=1,d=0,n=b;a;a=t)t=d-b/a*c,d=c,c=t,t=b%a,b=a;return b-1?0:(d+n)%n;}

Try it online!
Extended Euclidean algorithm, iterative version

APL (Dyalog Unicode), 36 38 bytes
{⌈/i×1=⍵|(i←⍳⍵)×⍵|⍺}

Try it online!
Explanation:
                   ⍵|⍺} ⍝ Get ⍺ mod ⍵
             (i←⍳⍵)×     ⍝ Multiply the result by all numbers up to ⍵
          ⍵|            ⍝ Take result mod ⍵
     i×1=                ⍝ Find all numbers (1,⍵) where the mod is 1
{⌈/                      ⍝ And take the largest

Much thanks to Adam in the APL Orchard chatroom for the help with this one!
Formula obtained from this site
First iteration:
{((⍵|⍺),⍵){+/⌈/⍵×1=(¯1↑⍺)|⍵×⊃⍺}⍳⍵}

what about larger tests? the challenge says: "The program should finish at some point, and should solve each test case in less than 60 seconds"

we usually count 1 char = 1 byte in apl

Python 3.8, 22 bytes
lambda a,b:pow(a,-1,b)

Obligatory Python 3.8+ builtin. Outputs the result, or gives the error ValueError: base is not invertible for the given modulus if there is no result.
Try it online.
Explanation:
To quote the Python 3.8 release notes:

For integers, the three-argument form of the pow() function now
permits the exponent to be negative in the case where the base is
relatively prime to the modulus. It then computes a modular inverse to
the base when the exponent is -1, and a suitable power of that inverse
for other negative exponents. For example, to compute the modular
multiplicative inverse of 38 modulo 137, write:
>>> pow(38, -1, 137)
119
>>> 119 * 38 % 137
1

Modular inverses arise in the solution of linear Diophantine equations. For example, to find integer solutions for 4258 + 147 = 369, first rewrite as 4258 ≡ 369 (mod 147) then solve:
>>> x = 369 * pow(4258, -1, 147) % 147
y = (4258 * x - 369) // -147
4258 * x + 147 * y
369

(Contributed by Mark Dickinson in bpo-36027.)

[Pyt], 1 byte
ɯ

Try it online!
Takes inputs in the order b a (on separate lines). Outputs None if there is no such multiplicate inverse. Gotta love built-ins.

Jelly, 27 bytes
²%³
⁴Ç⁹Ð¡x⁸
ÆṪ’BṚçL$P%³×gỊ¥

Try it online!
Uses Euler's theorem with modular exponentiation. Since Jelly doesn't have a builtin to perform modular exponentiation, it had to be implemented, and it took most of the bytes.

Axiom, 99 bytes
w(a,b,x,u)==(a=0=>(b*b=1=>b*x;0);w(b rem a,a,u,x-u*(b quo a)));h(a,b)==(b=0=>0;(b+w(a,b,0,1))rem b)

it use the function h(); h(a,b) return 0 if error [not exist inverse] otherwise
it return the z such that a*z mod b = 1
This would be ok even if arguments are negative...
this would be the general egcd() function that retunr a list of int (so they can be negative too)
egcd(aa:INT,bb:INT):List INT==
   x:=u:=-1   -- because the type is INT
   (a,b,x,u):=(aa,bb,0,1)
   repeat
      a=0=>break
      (q,r):=(b quo a, b rem a)
      (b,a,x,u):=(a,r,u,x-u*q)
   [b,x, (b-x*aa)quo bb]

this is how use it
(7) -> h(31,73714876143)
   (7)  45180085378
                                                    Type: PositiveInteger

i find the base algo in internet from https://pastebin.com/A13ybryc

Python 2 + sympy, 74 bytes
from sympy import*
def f(a,m):i,_,g=numbers.igcdex(a,m);return g==1and i%m

Try it online!
Taken from Jelly source code.

JavaScript (ES6), 42 41 39 38 bytes
Outputs false for no match. Will throw a overflow error as the second number gets to be too large.
x=>y=>(g=z=>x*z%y==1?z:z<y&&g(++z))(1)

Python 2, 52 bytes
-3 bytes thanks to Mr. Xcoder.
f=lambda a,b,i=1:i*a%b==1and i or i<b and f(a,b,i+1)

Try it online!
Outputs False on no solution and errors out as b gets larger.
Embedded TIO
I'm just testing out iframes in Stack Snippets and they work absolutely fantastic.

html,body{height:100%;}iframe{height:100%;width:100%;border:none;}
<iframe src="https://tio.run/##PY3BCsIwEETv/Yq5CEndy6ZotbhfIh4SanBB09Lm4tdHU8HTvIHhzfzOjym5UqI8/SuMHp4CqfCgrd8FEfZphGJaoJeAWqLZJnu2Jd/XvEJwNUxwlmA6wrFmTzj1FdzhT4QzV@DuR7emidULTdhMA@ZFU/4@tGrLBw"></iframe>

I'm not certain this works, can't i*a%b be 0?

Fails with "maximum recursion depth exceeded" error for input (31,73714876143).

Axiom, 45 bytes
f(x:PI,y:PI):NNI==(gcd(x,y)=1=>invmod(x,y);0)

0 for error else return z with x*z Mod y =1

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Application screen shot
Write the minimal code you need to take a screenshot of your application window. I am not asking for a function or program; just only a code segment.
It has obviously to be a GUI application; console applications not allowed.
Input:
None.
Output:
The valid outputs are:

Clipboard. Then post a screenshot of the Paste contents on a drawing program.
A file. Upload it somewhere and post a link to it here.
Inside any other window different from the window that was shoot. Post screenshot of the new window here.

As it is code-golf minimum number of characters wins!

Sandbox: https://codegolf.meta.stackexchange.com/a/12564/29325

Sounds like a VB program

The odd part about this is what defines "my application window."  Do I have to create a GUI and then screenshot it?  Does my language have to be run in a GUI eg Matlab's GUI?  GUIs don't generally exist for the code on this site, with the notable exception of that guy who uses Operation Flashpoint scripting.

"It has obviously to be a GUI application; console applications not allowed." - may we not copy the console's GUI window itself?

I feel like this is a dupe...

@programmer5000: Me too ...

@programmer5000: a dupe of what?

@Shaggy: a dupe of what?

? A previous challenge, obviously!

does your application window include the border (e.g. the close/minimize/maximize buttons) or can it be only the contents of the widow?

@dzaima: It should include the client an non-client area, otherwise is not a screenshot of the window, but of the client area.

@Shaggy: feels like the dupe of the of sandbox matching post? :S

@dzaima: unless your application window has no non-client area and when you create it, be default the creation is without the surrounding border.

@JonathanAllan: fixed input description.

@JonathanAllan: How do you get a screenshot from a console application?

The console may be inside some window (it would be on Windows or Mac at least) and you ask only for a snippet - I don't know how, but I also don't see why it would not be possible.

@DirtyDev : It seems not be a valid reason. The are lots of [tag:graphical-output] challenges which many languages do not support, and frankly, who cares?

@JonathanAllan: If you mean something like https://cn.pling.com/img//hive/content-pre1/70575-1.png , having the surrounding frame, it is acceptable . If you mean something like https://cdn.pcsteps.com/wp-content/uploads/2015/09/Basic-Linux-Commands-for-Linux-Terminal-Beginners-01.png it is not acceptable.

Yes, I mean the former (with frame) as I believed was implied by "your application window" - although you may want to add that detail (that including the frame is a requirement) to the post for clarity's sake.

@programmer5000 This deleted post might be the dupe you're thinking of

Java 8, 82 80 77 bytes
Class that extends Frame:
ImageIO.write(new Robot().createScreenCapture(bounds()),"png",new File("a"));

Regular Class 98 Bytes:
ImageIO.write(new Robot().createScreenCapture(Frame.getFrames()[0].bounds()),"png",new File("a"));

Uses deprecated bounds() method.

seems to me that f is not valid and should be something like
(this->) GetParentWindow() Java equivalent?

@sergiol ok I'll do that

You'll need to fully qualify ImageIO, Robot, and File, or include import statements.

@sergiol Do I need imports or full names even though it's a snippet?

@geokavel: no. But you should post also a version of it, without deriving from Frame.

@sergiol If it does not need to create references then couldn't the code just be x(); where x has been defined to do all the work?!

@JonathanAllan: Of course, no. The geokavel's code is nice.

@geokavel: My answer https://codegolf.stackexchange.com/a/122000/29325 has two versions: one inside a CWnd derived class, and another on a global/elsewhere scope

@JonathanAllan deleted my comment, as I didn't read thoroughly... apologies.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to pluralize ellipsis?
It's obviously ellipsisessieses.
Inspired by a chat message.
Your challenge
Given a list or space or comma-separated string of words, ellipsisessiesesify them.
To ellipsisessieses-ify a word:

Start with the word.
Add the first letter of the original word to the end.
Add 2 of the last letter of the original word to the end.
Add the second-to-last letter of the original word to the end.
Add the first letter of the original word to the end.
Add the last letter of the original word to the end.
Repeat steps 5 & 6 once.
You're done!

You can assume:

The input words will only be alphanumeric
Input & output can be a space-separated string or list
The input will contain only words
The words will be at least 2 letters long
The input will match the regex /^[a-z0-9]{2,}( [a-z0-9]{2,})*$/i
You can have a different input and output format
More to come...

Test cases:
ellipsis -> ellipsisessieses
goat -> goatgttagtgt
covfefe -> covfefeceefcece
programmer5000 -> programmer5000p000p0p0
up vote down goat -> upuppuupup voteveetveve downdnnwdndn goatgttagtgt
it is golf yo -> itittiitit isissiisis golfgfflgfgf yoyooyyoyo
crossed out 44 is still 44 -> crossedcddecdcd outottuotot 4444444444 isissiisis stillslllslsl 4444444444

Shorteststtsstst answerarrearar ininniinin bytesbssebsbs winswssnwsws!

Pretty sure the "e"s in "ellipsisessieses" is from "ellipses" (except the first "e")

I still don't know how to pluralize ellipsis... EDIT: apparently, it's ellipses.

For step 2, I think it should just be add an e, not add the first letter

It's ellipses. Other plurals that have the same spelling but different pronunciation for a word ending in -is and a word ending in -e are axes and bases.

JavaScript (ES6), 58 57 bytes
NB: This turns out to use the same trick as Jonathan Allan in this Jelly answer (though I noticed after posting).
Saved 1 byte thanks to Jonathan Allan
Works on arrays of strings.
s=>s.map(s=>s+'01120101'.replace(/./g,n=>s.substr(-n,1)))

Test cases

let f =

s=>s.map(s=>s+'01120101'.replace(/./g,n=>s.substr(-n,1)))

console.log(f(['ellipsis']))
console.log(f(['goat']))
console.log(f(['covfefe']))
console.log(f(['programmer5000']))
console.log(f(['up', 'vote', 'down', 'goat']))
console.log(f(['it', 'is', 'golf', 'yo']))
console.log(f(['crossed', 'out', '44', 'is', 'still', '44']))

Woah, this is cool! Nice job!

I believe you can save a byte by replacing 21102121 with 01120101 and n-2 with -n.

@JonathanAllan Good catch. Thanks!

Jelly,  13 12  11 bytes
⁽×ʠb3’ịṭµ€K

A full program that takes a list of lists of characters and prints the space separated output.
Try it online!
How?
⁽×ʠb3’ịṭµ€K - Main link: list of lists of characters e.g. ["this","is","it"]
        µ€  - for each word in the input:            e.g. "this"
⁽×ʠ         -   base 250 literal 5416                     5416
   b3       -   converted to base 3                       [2,1,1,0,2,1,2,1]
     ’      -   decrement                                 [1,0,0,-1,1,0,1,0]
      ị     -   index into the word                       "tssitsts"
       ṭ    -   tack to the word                          ["this",["tssitsts"]]
          K - join the results with spaces                ["this",["tssitsts"]," is",["issiisis"]," it",["ittiitit"]]
            - implicit print                              thistssitsts isissiisis itittiitit

Alternatively a list of words to list of words is also possible in 11 bytes:
⁽×ʠb3’ị;@µ€

⁽×ʠb3’ may also be replaced by 4,⁵Bj- for the same byte count
([4,10] in binary is [[1,0,0],[1,0,1,0]] joined by -1 is [1,0,0,-1,1,0,1,0]).

Do you need to join the results with spaces? You are allowed to output a list / a list of lists.

@programmer5000 Yeah, joining with spaces is optional here

@programmer5000 There is an alternative 11 byter that returns a list which I have given below the main answer (note that there is no way to get the main one down to 10 by removing the K because as a monadic link the returned list would not be one level deep, which I imagine is pushing lax I/O too far - that is for an input of ["this", "is", "it"] the return value would be [['t','h','i','s',"tssitsts"],['i','s',"issiisis"],['i','t',"ittiitit"]] (where "..." are lists of characters) and leaving it to print as a full program would smash it all together as thistssitstsisissiisisitittiitit)

05AB1E, 12 bytes
εD•Lz•3вÍèJ«

Try it online!
Explanation
ε              # apply on each word in input
 D             # duplicate the word
  •Lz•         # push the base-255 compressed number 5416
      3в       # convert to a list of base-3 digits (yields [2, 1, 1, 0, 2, 1, 2, 1])
        Í      # subtract 2 from each (yields [0, -1, -1, -2, 0, -1, 0, -1])
         è     # index into the word with these numbers
          J    # join to string
           «   # append to the original word

Hehe, great minds...

@JonathanAllan: Yeah, we had exactly the same idea it seems. Jellys shorter compression won the day this time :)

Retina, 52 49 bytes
3 bytes thanks to Arnauld.
(\w)(\w+)
$1$2$1
(.)(.)(.)\b
$1$2$3$2$2$1$3$2$3$2

Try it online!

That third line of code reminds me of a mutant from Total Recall.

@JonathanAllan Who was inspired by Eccentrica Gallumbits mentioned in the Hitch-Hiker's Guide to the Galaxy.

Python 2, 56 bytes
lambda s:[i+i[0]+i[-1]*2+i[-2]+(i[0]+i[-1])*2for i in s]

Try it online!
I think this is my fastest FGITW and it's not even that impressive. :P

Python 3, 60 bytes
lambda k:[x+''.join(x[-int(i)]for i in"01120101")for x in k]

Try it online!

Charcoal, 20 bytes
Ｆ⪪Ｓ «ι↑Ｅ”o∨↙8”§ι±Ｉκ→

Try it online! Link is to verbose version of code. Only happened to read @Arnauld's answer after coding this but this is basically a port of it. Explanation:
Ｆ   «                   Loop over
  Ｓ                     Input string
 ⪪                       Split at spaces
     ι                  Print the word
        ”o∨↙8”          Compressed string 01120101
       Ｅ                Map over each character
                 Ｉκ     Cast character to integer
                ±       Negate
              §ι        Circularly index into word
      ↑                 Print array upwards, prints each element rightwards
                    →    Move right

18 bytes maybe?

@ASCII-only Wouldn't you have to add extra bytes for the -rs flag?

Not sure, I guess so? -rs is there just to disable printing the input prompt though

Should I just make -rs mode the default instead?

sed, 46 bytes
s/^\(\(.\).*\(.\)\(.\)\)$/\1\2\4\4\3\2\4\2\4/g

Try it online!

Wolfram Language/Mathematica, 66 bytes
StringJoin[StringSplit[#,""]/.{a_,___,b_,c_}:>{#,a,c,c,b,a,c,a,c}]&

Just whipped it up real quick, might have a minor improvement here or there.

Dyalog APL, 51 49 bytes
Requires ⎕ML←3
∊{⍺,' ',⍵}/{S←1,L←≢⍵⋄⍵,⍵[∊S(L-0 1)S S]}¨' '(≠⊂⊢)⍞

-9 bytes thanks to @Adám in chat!
Try it online!

JavaScript (ES6), 74 60 bytes
s=>s.map(s=>s+(a=s[l=s.length-1],b=s[0])+a+a+s[l-1]+b+a+b+a)

Takes input as an array, and outputs an array.
-9 bytes thanks to Programmer5000
Test cases:

let f=

s=>s.map(s=>s+(a=s[l=s.length-1],b=s[0])+a+a+s[l-1]+b+a+b+a)

console.log(JSON.stringify(f(['ellipsis']))) // ellipsisessieses
console.log(JSON.stringify(f(['goat']))) // goatgttagtgt
console.log(JSON.stringify(f(['covfefe']))) // covfefeceefcece
console.log(JSON.stringify(f(['programmer5000']))) // programmer5000p000p0p0
console.log(JSON.stringify(f(['up', 'vote', 'down', 'goat']))) // upuppuupup,voteveetveve,downdnnwdndn,goatgttagtgt
console.log(JSON.stringify(f(['it', 'is', 'golf', 'yo']))) // itittiitit,isissiisis,golfgfflgfgf,yoyooyyoyo
console.log(JSON.stringify(f(['crossed', 'out', '44', 'is', 'still', '44']))) // crossedcddecdcd,outottuotot,4444444444,isissiisis,stillslllslsl,4444444444

Mathematica, 89 bytes
((f[a_]:=#~StringTake~a;k=#<>(q=f@1)<>(w=f[-1])<>w<>f@{-2}<>q<>w<>q<>w)&/@StringSplit@#)&

There's no mathematica Ellipsisessieses builtin? :(

Pyth, 17 bytes
Uses the same trick as in @Jonathan's answer.
m+dsm@dttkj5416 3

Try it here! or Check out the test Suite (Give it some time).
Port of my Python solution, 19 bytes 18 bytes:
m+dsm@d_k+0j1144 3

Paradoc (v0.2.10), 13? bytes (CP-1252)
µ96Qó3BÌDX=v+

Try it online!
Takes a list of words, and results in a list of words on the stack.
A small variation on the base-3 trick. Maybe it's time to work on my base 250-whatever compressor.
Explanation:
μ             .. Map the following block over each word (the block is
              .. terminated by }, but that doesn't exist, so until EOF)
              .. (The word is on the stack now.)
 96Qó         .. 96 * 26 (Q in base 26) = 2496, a hack to prevent us from
              .. needing a space to separate this from the following number.
     3B       .. Convert 2496 to base 3 to get [1,0,1,0,2,1,1,0]
       ÌD     .. Negate and reverse to get [0,-1,-1,-2,0,-1,0,-1]
         X    .. Push the loop variable: the word being mapped over
          =v  .. Index, vectorize; map over the indices by indexing them
              .. into the word
            + .. Concatenate with the original word

(Byte-counting question: Now that I'm actually demonstrating this in TIO, it take a list of words on the stack and results in a list of words on the stack, but you can't really do much with that list of words unless you close the block started by µ. Should I count that closing brace?)

Should I cound that closing brace? Yes, if you need it.

C# (.NET Core), 106 bytes
n=>{for(int i=0,x;i<n.Length;){var h=n[i];x=h.Length-1;char y=h[0],j=h[x];n[i++]=h+y+j+j+h[x-1]+y+j+y+j;}}

Try it online!
Lambda function that takes input as array of strings, and modifies original array for output

Charcoal, 38 30 bytes
-8 bytes thanks to ASCII-only.
Ｆ⪪Ｓ «ι§ι⁰×²§ι±¹§ι±²×²⁺§ι⁰§ι±¹

Try it online! Link is to verbose version.
Note the trailing space.

Perl 5, 55 49 + 1 (-a) = 56 50 bytes
used a trick from @Arrnauld's post to save a couple bytes
say map$_.'01120101 '=~s/\d/substr$_,-$&,1/egr,@F

Try it online!

Java 8, 117 bytes
a->{int i=0,l;for(String s:a){char c=s.charAt(0),d=s.charAt(l=s.length()-1);a[i++]+=""+c+d+d+s.charAt(l-1)+c+d+c+d;}}

Takes the input as a String-array, and modified this original array instead of returning a new one to save bytes.
Can most likely be golfed some more..
Explanation:
Try it here.
a->{                          // Method with String-array as parameter and no return-type
  int i=0,                    //  Index-integer (starting at 0)
      l;                      //  Length-integer which we use multiple times
  for(String s:a){            //  Loop over the input array
    char c=s.charAt(0),       //   The first character of the word
         d=s.charAt(          //   The last character of the word
            l=s.length()-1);  //    and set `l` at the same time to `length()-1`
    a[i++]+=                  //   Append to the current value in the array:
      ""                      //    String so the characters aren't appended as integers
      +c                      //    + the first character
      +d+d                    //    + two times the last character
      +s.charAt(l-1)          //    + the single-last character
      +c+d+c+d;               //    + the first + last character two times
  }                           //  End of loop
}                             // End of method


text:
Find Primes in Pi
Primes are everywhere...
they hide inside Pi
3.1415926535897932384626433832795028841971693993751
Let's get those primes!
The Challenge
Given as input an integer n>0, find out how many primes are hidden inside the first n digits of Pi
Examples
For n=3 we should search for primes in [3,1,4]. There are 2 Primes (3,31), so your code should output 2
For n=10 , the first 10 digits are [3,1,4,1,5,9,2,6,5,3] and your code should output 12 because [2, 3, 5, 31, 41, 53, 59, 653, 4159, 14159, 314159, 1592653] were hidden (and found!)
Test Cases
input -> output
1->1
3->2
13->14
22->28
42->60
50->93

150->197
250->363
500->895

Rules
Your code must be able to find all primes at least for n=50
Yes, you can hardcode the first 50 digits of Pi if you like
Entries hardcoding the answers are invalid
This is code-golf.Shortest answer in bytes wins!

"you can hardcode the first 50 digits of Pi if you like". First problem solved! Now for the golfed primality test on up to 50-digit integers... O_o (This is a nice challenge, but solid math built-ins or libraries are probably required.)

First 50 values (thanks to Mathematica): [1, 2, 2, 3, 4, 8, 9, 9, 9, 12, 12, 12, 14, 21, 24, 25, 25, 28, 28, 28, 28, 28, 28, 28, 32, 33, 33, 39, 39, 42, 44, 44, 44, 44, 44, 44, 44, 48, 51, 54, 60, 60, 64, 72, 74, 79, 82, 88, 88, 93]

For math-illiterate languages: would it be against the spirit of the challenge to encode the results instead?

@Arnauld the spirit of challenge is... freedom!

@totallyhuman That sequence not even in OEIS yet! Time for your claim to fame?

IMO allowing hardcoding of the first 50 values is detrimental to this challenge. This challenge is basically two parts, 1) try to compress the first 50 values, or 2) actually do the challenge.

@JarkoDubbeldam That is exactly the reason I picked 50. If someone can't "actually do the challenge" or the language he/she knows can't do it, then there is a second chance which costs +50 bytes. Are you actually going to do the challenge or you are here just to downvote?

This has nothing to do with languages not being able to do it, Python for example should be able to properly calculate it, but there is no reason to do so, because hardcoding is that much shorter.

Usually in these kind of challenges, where calculation becomes harder/slower/memory intensive, it is enough for the program to work theoretically, instead of setting an arbitrary cutoff and allowing hardcoding.

Is it me, or are the entries hardcoding the answers against the rules (they only allow "Yes, you can hardcode the first 50 digits of Pi if you like")?

@TripeHound You are absolutely right! Entries hardcoding the answers are invalid

@BillSteihn Updating rules after there are several answers is against the spirit of this website. Have you posted this question in the Sandbox? You would have had feedback really early that hardcoded answers would come in.

@BillSteihn also, this should say: distinct primes.

Much of the above discussion could be eliminated and the problem made much more general and useful if instead of "pi", the program must handle an arbitrary string of digits.  "pi" could then simply be a test case (as could "e" and √2).

05AB1E,  10  8 bytes
-2 bytes thanks to Adnan (p vectorises)
<žsþŒÙpO

Try it online! (will work up to n=98413 but will be very slow even for n=50 due to the need to test such large numbers for primality - TIO times out at 60 seconds for n=50.)
How?
<žsþŒÙpO - implicitly push input, n
<        - decrement = n-1
 žs      - pi to that many decimal places (i.e. to n digits)
   þ     - only the digits (get rid of the decimal point)
    Œ    - all sublists
     Ù   - unique values
      p  - is prime? (vectorises) 1 if so, 0 otherwise
       O - sum
         - implicitly print the top of the stack

<žsþŒÙpO should work for 8 bytes

Ah yeah p vectorises thanks!

Yes! Finally a very short code golf answer that I actually understand! :D

Mathematica, 76 bytes
Tr[1^Union@Select[FromDigits/@Subsequences@#&@@RealDigits[Pi,10,#],PrimeQ]]&

Oh, no fair, I'm not familiar with Mathematica golf. :P (+1)

@totallyhuman We posted this at the same time. this is so weird!

I golfed my answer using some of the syntactical tricks but I kept the functions I used before. I hope you don't mind.

Tr[1^...] That is a clever way of finding the length of the list, nice!

Mathematica, 104 97 90 bytes
Length@DeleteDuplicates@Select[FromDigits/@Subsequences@First@RealDigits[Pi,10,#],PrimeQ]&

Hahahaha, I managed to make this work. I have no idea how to use Mathematica. XD
Input:
[50]

you posted some seconds ahead of me. and our answers are very much alike! +1

Are you sure about the numbers you just posted (double check the rounding of the digits) I see slightly different results using Python and sympy

@JonathanAllan 50 96 The OP says 50 digits contain 93 primes, so Sympy's accuracy might be off..?

@JonathanAllan Is Sympy using a probabilistic or a deterministic primality test? (Same question for Mathematica's PrimeQ.)

@Arnauld good point, not sure.

First deviation is at n=12: sympy's pi yields 3.14159265359 and finds 15 primes (rather than the 12 reported by Mathematica): [2, 3, 5, 31, 41, 53, 59, 359, 653, 4159, 14159, 314159, 1592653, 4159265359, 314159265359]

^... I see that the evalf of sympy means rounding occurs :/

@JonathanAllan which are the 15 sympy's primes?

@BillSteihn I listed them above - but I see that pi should be 3.14159265358 not 3.14159265359 (last digit). I thought adding 1 to the digit length and truncating would have avoided that, but I was wrong.

@Downvoter I'm afraid I must sincerely ask you. Why? ;-;

Python 3, 274 237 207 194 189 bytes
-37 bytes thanks to Wheat Wizard! -14 bytes thanks to Mr.Xcoder.
Hardcodes the first 50 digits of pi but manually computes everything else.
x=int(input());l="31415926535897932384626433832795028841971693993751"[:x]
print(sum(all(i%m for m in range(2,i))for i in{int(i)for w in range(x)for i in[l[j:j-~w]for j in range(x-w)]}-{1}))

Try it online!

You could save a bunch of bytes

l=list("31415...) should save ~40 chars. And that change lets you replace map(str,i) with just i.

You could save another bunch of bytes (200)!

195 bytes by removing some strange code.

194 bytes by declaring len(l)

Jelly, 59 32 bytes
-27 bytes thanks to Erik the Outgolfer.
“!⁶⁷¬,6½ạEC.wʠ€Ẉ!+Ẉfṭ¡’Ṿḣ³ẆVQÆPS

Try it online!
Explanation
“...’Ṿḣ³ẆVQÆPS

“...’           compressed string that evaluates to first 50 digits of pi (314159...)
     Ṿ          uneval; stringify
      ḣ³        first n characters of the string where n is the first command-line argument
        Ẇ       all sublists
         V      convert all elements to integers
          Q     deduplicate
           ÆP   convert all prime elements to 1 and others to 0
             S  sum

Why did you spam this with answers?

Because nobody else was answering, and I hit rep cap anyways. :P

R, 156 123 bytes
cat(cumsum(c(1,1,0,1,1,4,1,0,0,3,0,0,2,7,3,1,0,3,0,0,0,0,0,0,4,1,0,6,0,3,2,0,0,0,0,0,0,4,3,3,6,0,4,8,2,5,3,6,0,5))[scan()])

Super interesting solution. Working on a proper one.
Saved 33 bytes thanks to @Giuseppe.
R (+ numbers and gmp), 198 bytes
function(n,x=unique(gmp::as.bigz(unlist(sapply(1:n,function(x)substring(gsub("[.]","",numbers::dropletPi(50)),x,x:n))))))min(length(x),sum(sapply(sapply(x[x>0&!is.na(x)],gmp::factorize),length)==1))

Proper solution. Takes n as input.
Uses numbers::dropletPi(50) to generate the first 50 decimal places of pi. gsub removes the decimal point. substring takes every possible substring (surprise surprise) of pi up to n.
The returned list is flattened and converted to gmp's bigz format. This format is required to store integers of length 50. unique takes the unique values of that vector. This result gets stored in x.
Then we check for primality. This is tricky, because there are a bunch of edge-cases and annoyances:

For high n, there is a 0 in pi. This leads to substrings with a leading zero. as.bigz produces NAs with that, which have to be removed.
On a similar note, the substring "0" will crash gmp::factorize, so has to be removed as well.
For n=1, x = 3. Which in itself is ok, but the bigz representation of 3 is iterable, so sapply will get confused and report 16 primes. To this end we take the minimum of the length of the vector x, and the amount of primes in it.
gmp::isprime can't seem to reliably handle the large numbers reliably. So instead we use gmp::factorize and check of the length of the output is 1.

So in all, we remove 0 and NA from x. We factorize all of x and check for the length. We count the number of occurrences of 1 and return the min(occurences, length(x)).

there you are! Now let's see if someone out there can outgolf this with a more interesting solution. could be you!

use cumsum(c(1,1,0,1,1,4,1,0,0,3,0,0,2,7,3,1,0,3,0,0,0,0,0,0,4,1,0,6,0,3,2,0,0,0,0,0,0,4,3,3,6,0,4,8,2,5,3,6,0,5)) instead of your vector for 123 bytes :)

@Giuseppe Nice one. That 'compression' will definitely beat any legit solution.

I think it's impossible in R without hardcoding or introducing another package since R has only 32-bit ints, which will certainly not represent a 50-digit integer.

The solution I am currently working on uses both numbers and gmp. The problem is getting a 50 digit representation of pi, along with primality tests for such values. numbers::dropletPi handles the first, but its isPrime is unsatisfactory. Same for gmp::isprime. So I am currently using gmp::factorize and checking for length()==1. However, for n=1 we would get a bigz representation of 3, which is iterable in itself (because of how bigz works) so it throws off sapply.

Maybe this can be turned into a recursive solution, removing one of the sapply calls in the definition of x. I seem to be thinking a lot in terms of recursion lately....

Yeah, I may think about this some more as well. 82 hardcoded bytes

Entries hardcoding the answers are invalid. You may only hardcode the first 50 digits of Pi. I think you should remove the first answer

161 bytes

@Giuseppe I can't run this yet, but by the looks of it, would "028" and "28" be counted as duplicates? I don't see anything that accounts for this

@JarkoDubbeldam you're right, it'll crash on that, and for 0 as well...

161 bytes, again (I actually tested this time :P)

Husk, 9 bytes
#ṗumdQ↑İπ

Try it online!
Freezes beyond n=10 on tio. Reverse of the 05AB1E program.


text:
Pick up your phone! It's vibrating!
You just recently got a new phone, but you don't quite like the way it vibrates, you've decided you want to create your own vibration patterns. So, you've written a program where you used the keywords long, short and pause to make your phone vibrate according to these keywords.
Task
Create a small program that accepts a string of long, short, and pause and outputs another string representing the phonetic sound of a phone vibrating; Rrrr - Rr
long sounds are Rrrr
short sounds are Rr
(Casing matters)
pause is a dash -
all sounds are delimited by dash with surrounding spaces ' - '
Test Cases
input:   long long short long short
output: Rrrr - Rrrr - Rr - Rrrr - Rr
input:   long long long short short short
output: Rrrr - Rrrr - Rrrr - Rr - Rr - Rr
input:   short short short pause short short short
output: Rr - Rr - Rr - - - Rr - Rr - Rr
input:   long short short long long pause short short
output: Rrrr - Rr - Rr - Rrrr - Rrrr - - - Rr - Rr
This is a code-golf question so answers will be scored in bytes, with the fewest bytes winning.

Which exactly "sounds" can be used? For example, what about Mmm and M?

"Any sound, as long as it sounds like a vibrating phone, can be used"

Isn't that a subjective criterion? I would like to use empty string, it sounds like a vibrating phone to me.

I realize now that one could totally use no characters. Alright, I'll fix my question.

Your "sounds like" rule is much too vague. I'd suggest just requiring exact strings. Code golf requires precise criteria so we can optimize code without having argument on whether an improvement is valid.

Can we take input as a list of words?

Do we have to delimit the sounds with a -? This is the case in your example, but is not specified anywhere.

About to post a C solution, removing the - delimiter would save me so many bytes...

The examples all use a capital lower followed by copies of a lowercased letter. Is this a rule?

What needs to be done before this can be reopened: 1) Specify the exact strings (or sets of strings) we must use, including case limitations, 2) Clarify whether input and/or output can be an array either of words or arrays of characters, 3) Specify the exact separator that must be used when outputting as a string.

Without all of the above a (quick) Japt port of muddyfish's Pyke solution could be anywhere between 12 and 24 bytes long.

Half of the answers are now invalid due to the changes. I would have allowed all 2 or 4 letter strings.

And there is still the problem of the delimiter. Must it be - as stated by the examples, or can we use whatever delimiter is best for our language of choice?

You have yet to clarify points 2 & 3 above, as well as the second part of point 1 (casing).

The examples include spaces but the description does not (it implies Rrrr-Rr---Rr-Rrrr is a valid output given the input long short pause short long for example). Are the spaces mandatory or not?

Pyke, 22 20 bytes
cFh.o6.&\R*\-|l4)J" -

Try it here!
c                      -  split(input, " ")
 Fh.o6.&\R*\-|l4)      -  for i in ^:
  h                    -        ^[0]
   .o                  -       ord(^)
     6.&               -      ^ & 6
        \R*            -     ^
           \-|         -    ^ or "-"
              l4       -   ^.title()
                 J" -  - " - ".join(^)

The crux of this answer is the transformation of ["long", "short", "pause"] into [4, 2, 0]. It gets the code point of the first letter of each word and ANDs it with 6. By lucky coincidence it transforms to the values we're looking for. (I searched through quite a few other longer solutions before finding this one). Once that's done, we can further transform that list of ints into ["RRRR", "RR", ""] by multiplying our int by "R" which then turns into ["RRRR", "RR", "-"] and finally title casing it to get ["Rrrr", "Rr", "-"]. We then join the resulting list by " - "

Cool way of going about it with the transformation!

The solution is absurdly similar in Pyth: j" - "m|*\M.&Chd6\-c :-)

Also The OP adds space to the examples but does not specify them, I've asked for clarification on that.

@JonathanAllan The bytes \xef and \xa6 are .o and .& respectively. It's a backwards compatible change where if the high bit is set, it runs it like the old 2 byte commands. I'm writing it this way to make it easier for the reader and because Pyke technically doesn't use a code page anymore and I don't want to have to insert random bytes that don't work

JavaScript, 70 63 bytes
2 bytes saved thanks to Luke
a=>a.replace(/./g,a=>[['Rr','rr','-',' - ']['onp '.search(a)]])

Try it online!

Nice trick with the outer []s!

Haskell, 71 66 59 bytes
g 'o'="Rr"
g 'n'="rr"
g 'p'="-"
g ' '=" - "
g _=""
f=(g=<<)

Try it online!
Oh right, =<< is concatMap.
Takes advantage of the fact that "long" and "short" both have the letter o.

You don't need to pay the 2 bytes for f= point-free functions are allowed without assignment

You can save one whole byte with lambdacase by switching to lambdabot haskell: (>>=(\case 'o'->"Rr";'n'->"rr";'p'->"-";' '->" - ";_->""))

05AB1E, 33 27 25 21 bytes
#εÇн6&'m×™'-)éθ}… - ý

Try it online!
Explanation
#                       # split input on spaces
 ε             }        # apply to each
  Çн                    # get the character code of the head
    6&                  # AND with 6
      'm×               # repeat "m" this many times
         ™              # title case
          '-)           # wrap in a list with "-"
             éθ         # get the longest string
                … - ý   # join to string using " - " as separator

Saved 3 bytes using the AND 6 trick from muddyfish's pyke answer

JavaScript (ES6), 65 59 bytes
s=>s.split` `.map(x=>x<'m'?'Rrrr':x<'q'?'-':'Rr').join` - `

let f =

s=>s.split` `.map(x=>x<'m'?'Rrrr':x<'q'?'-':'Rr').join` - `

console.log(f("long long short long short")); // => Rrrr - Rrrr - Rr - Rrrr - Rr
console.log(f("long long long short short short")); // => Rrrr - Rrrr - Rrrr - Rr - Rr - Rr
console.log(f("short short short pause short short short")); // => Rr - Rr - Rr - - - Rr - Rr - Rr
console.log(f("long short short long long pause short short")); // => Rrrr - Rr - Rr - Rrrr - Rrrr - - - Rr - Rr

Python 2, 76 69 64 bytes
lambda s:' - '.join('Rrrr'[:ord(b[0])&6]or'-'for b in s.split())

Try it online!
Alternates:
Python 2, 76 69 bytes
lambda s:' - '.join(['Rrrr','-','Rr'][ord(b[1])%3]for b in s.split())

Try it online!
Python 2, 69 bytes
lambda s:' - '.join('-Rrrr'['o'in b:8-ord(b[1])%9]for b in s.split())

Try it online!

Retina, 31 29 bytes
1 byte saved thanks to Dom Hastings
1 byte saved thanks to Neil
[^lhp ]

l
hrr
h
Rr
p
-

 -

Try it online!
This is different approach than @DomHastings's answer.

Mathematica, 81 bytes
StringReplace[#,{"long"->"Bzzz -","short"->"Bz -","pause"->"- -"}]~StringDrop~-2&

Try it online!

Röda, 73 57 47 46 40 44 bytes
f&a{a~=*`s\w+|l;Rr;ong;rr;p\w+;-; ; - `/";"}

Try it online!
+4 bytes due to rule change (must use Rrrr instead of any 4 letter variant).
Previous code:
{[[split()|["Bzzz"]if[_="long"]else["Bz"]if[_1="short"]else["-"]]&" - "]}

Using Mmm and Mm is 1 byte shorter.

@ATaco It's said in the question that "Long sounds should be 4 characters long, and short sounds should be 2 characters long".

ATaco, please note that the criteriums have been further specified in the question.

Perl 5, 39 bytes
37 bytes code + 2 for -pa.
$_=join" - ",map/p/?"-":Bz.zz x/l/,@F

Try it online!

R, 77 bytes
cat(c('Rrrr','Rr','-')[match(scan(,''),c('long','short','pause'))],sep=' - ')

Takes input through STDIN, checks whether the input matches long, short or pause and swaps the matches for Rrrr, Rr or - respectively.
This is then printed with - padded with spaces as separator, matching the desired output.

You can save 2 bytes by switching from match to %in%: scan(,'') %in% c('long','short','pause')

@YCR I don't think that'll work. a %in% b checks whether entries in the a are present in b, while match(a, b) returns the actual indices of the matches. Since we can assume that the input is valid, using %in% would just return a vector of TRUEs.

Arf, true. I have test it with c('long','short','pause').

That's because when you feed a boolean vector into [, it is interpreted as [which(bool) == TRUE], which in your example would be [c(1,2,3)], which in turn happens to give the correct output.

Instead of sep=' - ' you can use s=' - ' for 2 bytes less

@Rift that doesn't work for me, it just appends - to the print. Partial matching doesn't really play nice with ... arguments.

C (gcc), 93 77 76 bytes
-2 bytes thanks to Scepheo!
-1 byte thanks to Cyoce!
Takes a NULL terminated **char or equivalent as an input.
f(char**a){for(;*a;*++a&&printf(" - "))printf(**a&6?**a&1?"Rr":"Rrrr":"-");}

Try it online!
Explanations:
f(char**a){
  // While the string at the current position is not NULL
  for(;*a;
    // Advances the pointer to the next string
    // Then if the current string is not NULL, prints a delimiter
    *++a&&printf(" - ")
  )
    /*
      If the 1st char of the string is not a 'p'
        If the 1st char is not a 'l'
          Prints "Rr"
        Else
          Prints "Rrrr"
      Else:
        Prints "-"
     */
    printf(**a&6?**a&1?"Rr":"Rrrr":"-");
}

I think you can combine a++,*a into *++a to save two bytes, and take advantage of the vague "sound" definition to use *a instead of "Rrrr" to save another four bytes.

Your second suggestion is genius!

Can you move part of the increment stage of the for-loop to the body instead of being comma-separated?

This indeed saves a byte. Good catch!

R, 72 bytes
Takes input from stdin, prints to stdout.
cat(sapply(scan(,''),switch,long="vvvv",short="vv",pause="-"),sep=" - ")

Try it online!

Batch, 88 bytes
@set/ps=
@set s=%s: = - %
@set s=%s:long=Rrrr%
@set s=%s:short=Rr%
@echo %s:pause=-%

Takes input on STDIN. Unfortunately loop overhead costs 26 bytes so this is just boring replacements.

Suggested edit to remove all of the @s

@Stephen Yes, I got the notification...

Nice! Just two things, though: I counted that answer to be 84 bytes long, not 88. Also, OP has replaced Mmmm and Mm with Rrrr and Rr, it would be nice to update your answer c:

Batch as of what platform?  I doubt MS-DOS 6.22 would do what XP does when in enhanced command mode.

@TOOGAM Yeah, when I say Batch I usually mean Windows NT's CMD.EXE's version.

Vim (52 bytes)
:s/long/Rrrr/ge|s/short/Rr/ge|s/pause/-/ge|s/ / - /genter
Can probably be made shorter...

Stringing the commands together like this stops the train if one of them errors IE if there's no pause or something in the given string, the replacements after the one that failed won't work.  You can either split them on separate lines or put an e flag at the end

Corrected the error. I still feel there ought to be some way to speed it up, but the only other way I thought of (after turning "pause" into a dash, s/[^ -]/r/, capitalize the first R after every space, trim four-r to two-r) came out longer.

Retina, 31 bytes
short|l
Bz
ong
zz
pause
-

 -

-1 byte thanks to @fergusq!
Try it online!

PHP, 113 bytes
<?$s=[];for($i=1;$i<$argc;$i++){$c=$argv[$i][0];$s[]=($c<'m')?'Rrrr':(($c<'q')?'-':'Rr');}echo implode(' - ',$s);

Try it online!
First attempt at code golf, so probably a lot of optimisations available!

V, 32 bytes
Í /ò
çl/CRrrr
ço/CRr
çp/-
HòJa-

Try it online!

AutoIt, 145 bytes
EXECUTE(STRINGREPLACE('MSGBOX(0,0,STRINGSTRIPWS(====INPUTBOX(0,0),"PAUSE",""),"LONG","Rrrr"),"SHORT","Rr")," "," - "),4))',"=","STRINGREPLACE("))

(AutoIt is really bad choice for code golf, tried my best to make it small as possible)

Welcome to the site! :)

Sed, 50 bytes
Takes input from stdin, prints to stdout
s/l\w*/Rrrr -/g
s/s\w*/Rr -/g
s/p\w*/- -/g
s/ -$//

Edit - saved 2 bytes
Sed, 40 bytes
Copying idea from Nitrodon's answer
s/[srtaue]//g
y/lhongp/RRrrr-/
s/ / - /g

Edit: saved another 2 bytes

Alice, 37 bytes
/ lRnrhR
\""orgrp-""!yi'."?-e"ySNo?@/

Try it online!
Explanation
This program makes the following substitutions:

l, h → R
o, n, g → r
p → -
Space → Space
Everything else → Nothing

"longhp "!i.?eyN?"RrrrR- "y' " - "So@

"longhp "    Push this string
!            Immediately move to tape
i            Take input string
.            Duplicate
?ey          Remove all instances of the characters "longhp " from copy
N            Remove the remaining characters from the original, leaving only "longhp "
?"RrrrR- "y  Replace the characters in "longhp " with the corresponding characters in "RrrrR- "
' " - "S     Replace all spaces with " - "
o            Output
@            Terminate

Excel,  100 bytes
=REPLACE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"long","- Bzzz"),"short","- Bz"),"pause","- -"),1,2,"")

Per examples, Input is SPACE separated string, as is output.
Question itself does not mention a SPACE requirement, allowing for a slightly shorter 97 byte solution:
=REPLACE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"long","-Bzzz"),"short","-Bz"),"pause","--"),1,1,"")

Paradoc (v0.2.10), 21 bytes (CP-1252)
Wμ‹6&'r\°"-":Ãu}« rTc

Try it online!
Takes a string on the stack and results in a string on the stack. Prepend i to turn into a full program that reads from STDIN.
Uses &6 like the Pyke answer and everybody else, but joins the tokens together slightly differently, by adding a "-" token after each noise, deleting the last one, and then joining these tokens by spaces. Seems to save a byte over joining by " - ".
Explanation:
W                     .. Break into words
 μ             }      .. Map over this block:
  ‹                   .. Take the first character
   6&                 .. Binary AND with 6, to get 4, 2, or 0
     'r               .. Character "r"
       \              .. Swap top two of stack
        °             .. Replicate, to get "rrrr", "rr", or ""
         "-"          .. Push string "-"
            :         .. Duplicate on stack
             Ã        .. Compute the max...
              u       .. ... underneath the top of the stack (so, of the
                      .. second and third elements on the stack, i.e. the
                      .. string of "r"s and "-")
                      .. The mappped block ends here; we now have
                      .. something like ["rrrr", "-", "-", "-", "rr", "-"]
                «     .. Take all but the last
                  r   .. Join with spaces (this built-in's name is two
                      .. characters, the first of which is a space)
                   Tc .. Title-case

v0.2.11 will support shaving two more bytes by replacing \° with x and "-" with '-.

Ruby, 78 bytes
p ARGV[0].chars.map{|c|{p:'-',o:'Rr',g:'rr',' '.to_sym=>' - '}[c.to_sym]}.join

The only important parts of the input are p, o, g, and space... ignore the rest.

short becomes o
long becomes og
pause becomes p

Try it online!

Ruby, 67 bytes
p ARGV[0].split(' ').map{|w|w<'m'?'Rrrr':w<'q'?'-':'Rr'}.join ' - '

This is Johan Karlsson's JavaScript solution ported to Ruby. If you like this answer, you should upvote Johan's answer.
The key idea is to compare the word strings 'short', etc. to a single character in order to distinguish between words.
| Word  | < 'm' | < 'q' | Output |
|-------|-------|-------|--------|
| short | false | false | 'Rr'   |
| long  | true  | N/A   | 'Rrrr' |
| pause | false | true  | '-'    |

Or, in alphabetical order:

long
m
pause
q
short

Try it online!

Python 3, 66 bytes
' - '.join(['Rrrr','-','Rr'][ord(s[1])%3]for s in input().split())

Try it online!

Python 2, 69 bytes
lambda s:" - ".join((ord(i[0])&6)*"R"or"-"for i in s.split()).title()

Try it online!
Port of my Pyke answer

SOGL V0.12, 28 bytes
θ{K;⁄5κ« r*; p=?X┌}}¹" - ”∑ū

Try it Here!
fun fact: if it was allowed to delimit with  -   or   -  it'd be a byte shorter


text:
Read my free-form date
Given a date written in any (must handle all in the same program) of the following formats, parse it into a valid yyyy/mm/dd date.
17th May 2012
March 14th, 2016
20 February 2014
September 14, 2017
Sunday, June 8, 2015

Rules

Dates will sometimes be invalid, ie. incorrect day for the month or number of months in a year, you must handle both cases. Either by erroring out or returning a consistent falsey value, you choose. (They will however stick to the template formats above)
Padding for days and months less than 10 must be used to create a two digit output.
Month names will always be the full name, not shortened to their three character counterparts.
You can assume the year will always be within the 0000-9999 range.
Negative numbers need not be handled.
You can create a full program or function so output can be in any format, printed to console or returned from a function.
Input will always be a string, output must always be a string, if it makes it shorter to take it as a single argument in an array eg. ["17th May 2012"] you may do so and output can be the same ["2012/05/17"]
You can assume spelling in input will be correct.

BONUS: cos who here doesnt like a challenge ;)
If you can manage to also allow the input formats of The Fourteenth of March, 2016 or March the Fourteenth, 2016 you may take an extra 20 bytes off your code with any final byte counts less than 1 resulting in 1.
Here are the full written numbers for each of the days to avoid any confusion on spelling.
First, Second, Third, Fourth, Fifth, Sixth, Seventh, Eighth, Nineth, Tenth, Eleventh, Twelfth, Thirteenth, Fourteenth, Fifteenth, Sixteenth, Seventeenth, Eighteenth, Nineteenth, Twentieth, Twenty First, Twenty Second, Twenty Third, Twenty Fourth, Twenty Fifth, Twenty Sixth, Twenty Seventh, Twenty Eighth, Twenty Nineth, Thirtieth, Thirty First

Test Cases
INPUT                           | Output
17th May 2012                   | 2012/05/17
March 14th, 2016                | 2016/03/14
20 February 2014                | 2014/02/20
September 14, 2017              | 2017/09/14
Sunday, June 8, 2015            | 2015/06/08
1st January 1918                | 1918/01/01

The Fourteenth of March, 2016   | 2016/03/14
March the Fourteenth, 2016      | 2016/03/14
November the Seventeenth, 2019  | 2019/11/17
The Thirtieth of April, 2016    | 2016/04/30

30 February 2014                | Invalid
September 99, 2017              | Invalid
Sunday, June8, 2015             | Invalid

The Thirty First of April, 2016 | Invalid

"You can assume ... there will always be the at least one space between parts of the date". "Dates will sometimes be invalid ...They will however stick to the template formats above". Doesn't Sunday, June8, 2015 contradict the format?

0/10, not freeform enough

"cos who here doesnt like a challenge" - when they come in the form of a bonus, mostly all of us don't! And boo-urns to input validation.

@Timtech I see the confliction, i'll remove the always has a space rule

I don't see why the input format is so strict. IMHO it would be better to let us pick one.

sorry, @Mr. Xcoder, i want you to be able to parse any of the formats given without prior knowledge of the format.

@Mr.Xcoder I think the entire challenge is to support multiple input formats.. Things like 20 February 2014 are default supported in a lot of date-parsers, but 17th and Sunday, June 8, 2015 are a bit more difficult to parse (depending on the language).

@KevinCruijssen I think it's too much fluff, to handle 5 different formats. There is not much clever golfing to be done in this case. I personally dislike the task, if the whole point is to make our code have an if-else boilerplate or something.

@Mr.Xcoder I never said it was a fun/boring, easy/hard, good/bad code-golf challenge. I'm simply stating that based on what I read in the challenge, the multiple input-format supporting seems to be the main goal of the challenge. I agree it will most likely be an if-else for the five input-formats, or some kind of regex to extract the year, month and day (which is currently my approach).

@Mr.Xcoder  there shouldnt be much if-else going on as far as i can tell, you just need to cleverly parse a date part (day,month or year) from the string and output the three parts in the correct order

Can we please at least assume that the year always has four digits?

@Xynos But you're still saying that inputs "will however stick to the template formats above", and only possible error is wrong day for the month/year etc.

Can output be separated by hyphens (instead of slashes)?

Is outputting nothing valid for an invalid input?

Also test case request: February 29, 2017 and February 29, 2016

Is the day of the week always correct? Would Thursday, August 25, 2017 be valid? I see submissions ignoring the DOW.

@BenjaminCuningham Would Sunday, June 8, 2015 be valid? (It was a Monday.)

Given "You can assume spelling in input will be correct" and that all formats spell out the month names how can there ever be an input that has an incorrect number of months in a year? 2. Sunday, June8, 2015 in the examples does not fit any of the listed formats as it is missing a space ("They will however stick to the template formats above"), I imagine this is invalid because 2015/06/08 was not a Sunday, but that seems to not be a part of the previously mentioned possible ways for the input to be invalid (which comes back to Benjamin Cuningham's question).

Rails, 41, 37 35 bytes
->x{x.to_date.strftime('%Y/%m/%d')}

I don't know of an online interpreter for Rails, but here is a screenshot demonstrating this proc

Online interpreter link?

Does this really work for all the formats in question? :o

@totallyhuman Added a screenshot showing the results. Unfortunately I don't know of an online interpreter :(

PowerShell, 91 89 91 56 bytes
date("$args"-replace'th|rd|st|(\b.*)day|,')-f yyyy/MM/dd

Try it online!
Takes input as a string. Uses a -replace to get rid of junk, then uses the built-in Get-Date command with the -format flag to specify the required yyyy/MM/dd format. That string is left on the pipeline and output is implicit.
Saved two bytes thanks to Mr Xcoder. Saved a huge chunk thanks to TessellatingHeckler's regex golfing.

Hey look competitive PowerShell submission!

@EriktheOutgolfer Date manipulation is one of PowerShell's strengths.

Why do you have all those extraneous spaces?

@Mr.Xcoder "all those" = 2. lol. Thanks!

You can remove the '' from the date format, for -2. If you want to stick to your approach, given the "spelling is correct" then you can replace 'th|rd|st|(\b.*)day|,' and it drops to 56 bytes and handles the same cases. Although I think it's wrong because if you drop the days, you can't pick up the  Sunday, June8, 2015             | Invalid case because it was Monday. It should error, but it parses as valid. Not sure what the ruling on that will be, or if others are checking it.

@TessellatingHeckler That's an interesting point. I had interpreted the reason that was invalid was because it was missing a space, since in the valid section there is the same input with the space and it prints the date. I guess we'll see what the OP says. Thanks for the regex golf!

PHP, 73 164+1 bytes
for(preg_match("#(\d+)[^\d]+(\d+)#",$d=$argn,$r);$m++<12;)strpos(_.$d,date(F,strtotime($r[2].-$m)))&&printf(checkdate($m,$r[1],$r[2])?"$r[2]/%02d/%02d":E,$m,$r[1]);

Run as pipe with -nR or try it online.
The date check was really expensive: I had to disassemble the date before using a builtin, then try and error on the month name.

I think you have to support all formats not just one of them?

@EriktheOutgolfer it does. But not the bonus formats.

@EriktheOutgolfer This does handle all formats.

This fails for invalid dates. 30 February 2014 returns 2014/03/02. Either by erroring out or returning a consistent falsey value, you choose. (They will however stick to the template formats above)

@Mr.Xcoder That quite ruins it ...

I'm very sorry if it can't easily be fixed :'-(

@Mr.Xcoder Awfully expensive fix: +91 bytes. Your comment ineed added to the post. :D

Python 3 + parsedatetime library, 152 139 155 153 bytes
Saved 13 bytes thanks to Jonathan Allan
Added 16 bytes to handle dates with invalid length days
Saved 2 bytes by removing lambda assignment
lambda s:re.search(f'(^| ){str(h(s)[0].tm_mday)[:2]}[^\d]',s)and time.strftime('%Y/%m/%d',h(s)[0])
import parsedatetime as p,time,re
h=p.Calendar().parse

Try it online!
Does not support bonus dates

Welcome to PPCG! Nice first post. Save 13 bytes by using: the falsey return value of None; import ...as; & a lambda by reusing parse as h.

Python 2, 193 bytes
lambda s:time.strftime('%Y/%m/%d',time.strptime(re.sub(r'^(\w+) (\d+)',r'\2 \1',re.sub('^ ','',re.sub('(th|rd|st)|(Sun|Mon|Tues|Wednes|Thurs|Fri|Satur)day|,','',s))),'%d %B %Y'))
import re,time

Try it online!
;-; pls halp

;-; pls halp - 192 bytes by declaring time.

186 bytes (remove f= from the byte count on TiO) by declaring re.sub

Java (OpenJDK 8), 190 + 26 = 216 bytes
import java.time.format.*;

s->DateTimeFormatter.ofPattern("uuuu/MM/dd").format(DateTimeFormatter.ofPattern("[EEEE, ][d ]MMMM [d, ]uuuu").withResolverStyle(ResolverStyle.STRICT).parse(s.replaceAll("(\\d)[a-z].","$1")))

Try it online!
Important note: it was shorter to also validate the day of week instead of ditching it, so that validation is included!
I haven't tried with SimpleDateFormat beyond the obvious cases which all accepted dates like 30 February. So I had to ditch it and I used Java 8's DateTimeFormatter.
Explanation
"[EEEE, ][d ]MMMM [d, ]uuuu"

This format means :

optional day-of-week followed by comma and space [EEEE, ] (happens in Sunday, ...),
followed by optional day with space [d ],
followed by month in full letters MMMM and space,
followed by optional day with comma and space [d, ],
followed by year of era uuuu to let the parser know we're in Gregorian era.

Code:
import java.time.format.*;                                     // Required for DateTimeFormatter, *and* ResolverStyle

s->DateTimeFormatter.ofPattern("uuuu/MM/dd")                   // Output format
  .format(
    DateTimeFormatter.ofPattern("[EEEE, ][d ]MMMM [d, ]uuuu")  // Input format
      .withResolverStyle(ResolverStyle.STRICT)                 // Invalidates xxxx-02-30 instead of transforming it into xxxx-02-28
      .parse(
        s.replaceAll("(\\d)[a-z].","$1")                       // remove st, nd, rd, th
       )
    )

Credits

2 bytes in the regex thanks to Neil.

Do you need the brackets in the replaceAll pattern?

Looks like I don't. Thanks, @Neil!

JavaScript (ES6), 124 122 bytes

f=
s=>(d=new Date(s.replace(/.[dht]\b/,'')+' +0')).getDate()==s.match(/\d\d?/)&&d.toISOString().replace(/-(..)(T.*)?/g,'/$1')
<input oninput=o.textContent=f(this.value)><pre id=o>

Returns 2015/06/07 for June 8, 2015 (UTC issue? I'm in UTC+2)  and false for either Sunday, June 8, 2015 or Monday, June 8, 2015.

@OlivierGrégoire Thanks for pointing those out. I'd only tried dates in UK outside Summer Time so they were already using UTC, and I'd not tried weekdays ending in nday.


text:
Get thee behind me Satan-Prime!
Satan-Primes
who are they?
they are Primes containing 666
these are Satan-Primes:[46663,266677,666599,666683,616669]
these are NOT :[462667,665669,36363631,555]
Plot
Every number bigger than 6661 has Satan-Primes behind him
The Challenge
Given an integer n>6661 find the Satan-Prime behind (or equal) and closest to itself.
Examples
Integer n=30000 has 3 Satan-Primes(SP) behind it:[6661, 16661, 26669].
Your code must return 26669 which is the closest behind it
Test Cases
Input->Output
6662->6661
10000->6661
66697->66697 (a SP returns himself)
328765->326663
678987->676661
969696->966677

Rules
Yor code should work for any n in the range of your language.
This is code-golf, so the shortest answer in bytes wins!

define "about a minute." Is it +- 30 seconds? I personally think that 30 minutes and a minute don't differ that much... Also bonuses are generally frowned upon... also I think this might have been better as an output the nth satan prime challenge...

ok ok people... bonus will be removed...

Hope you don't mind the edit I made to the challenge title.

@Shaggy What point does the title change serve...?

@ConorO'Brien Rhyming and appearing archaic, I presume.

Neim, 9 bytes
>ͻ:D+6S÷

Explanation:
>         Increment input
 ͻ        Start infinite loop
  :        Previous prime
   D       Duplicate
    +6     Push 666
      S    Swap
          See if 666 is a substring of the top of the stack
        ÷  If true, break

Try it online!

So there's really a builtin to push "66 prepended to a digit"? O_O Neim has progressed.

How does +6 push 666? Or is Neim just that metal?

@RobertFraser Apparently +x means 612 + character code of x. The code of 6 happens to be 54, so 612+54=666.

@EriktheOutgolfer Well, Neim can represent all three digits numbers and a few four digits using two bytes.

@Okx Well, what are the builtins for that?

@EriktheOutgolfer '\+* = 100,356,612,868 (plus the ordinal of the following char that is)

@JonathanAllan Oh thanks! Docs are missing stuff...

there's actually a little ascii satan in the code... ͻ:D

Mathematica, 82 bytes
Last@Select[Prime@Range@PrimePi@#,!FreeQ[Subsequences[IntegerDigits@#],{6,6,6}]&]&

Wait, you mean there isn't a built-in for this one?

Jelly, 10 9 bytes
Saved 10% thanks to @Dennis!
ÆRwÐf666Ṫ

Try it online!
Explanation
ÆR          # All primes in range [2, input]
   Ðf      # Keep those which satisfy
  w        # truthy if y is in x
     666   #           ^ (this is y)
        Ṫ  # Tail (take the last element)

Alternative: ÆRẇ@Ðf666Ṁ

I love that the Tail (right after 666) looks like a cross.

w should work instead of ẇ@.

@Dennis s/sh/w/ of course it works :p

Pyth, 15 14 bytes
Saved 1 byte with help from Dave.
Memory errors for 969696 and anything higher on my machine, but it is fine if it is given enough memory.
ef&/`T*3\6P_TS

Try it here or check out the Test Suite.

How?

ef&/`T*3\6P_TSQ - Full program, with implicit input (Q) at the end

             SQ - Range [1,Q]
 f              - Filter.
          P_T   - Is prime?
  &             - And
   /`T*3\6      - It contains 666.
e               - Last element.
                - Implicitly output the result.

Pyth, 14 bytes
ef/`T*\63fP_TS

Try it here!

14 bytes: ef&/\T*3\6P_TS`

I added the ending Q by mistake, its 14

"666" is a less efficient way to describe the string 666 that *3\6

Bash + Core Utils, 51 49 Bytes
seq $1|tac|factor|awk 'NF==2&&/666/&&!a--&&$0=$2'

Takes command line argument. Can be quite slow with larger numbers.

This outputs all "satan primes" down to 6661, but it should only be printing the closest one below the input: try it online. One fix would be to just add |head -1 to the end.

@JustinMariner lol, whoops, fixed it

05AB1E, 11 bytes
ƒNpN666å*iN

Try it online!

Mathematica, 64 62 61 53 bytes
#//.i_/;!PrimeQ@i||ToString@i~StringFreeQ~"666":>i-1&

-1 byte thanks to @KellyLowder
-8 bytes (wow) thanks to @Notatree
Explanation
Take an input. We decrement it under these conditions:

the input is not prime, OR

the digits of the inputs does not contain three 6s in a row.

We repeat that until a Satan prime is reached.

Very nice.  You can lose one more _  at the end since a prime can't end in 6.

@KellyLowder good point

This is even shorter with strings: #//.i_/;!PrimeQ@i||ToString@i~StringFreeQ~"666":>i-1&

@Notatree wow! nice!

Japt, 14 bytes
õ fj w æ_sø666

Test it
Seeing as there was a 50% time-based bonus: Completes test case 969696 in under half a second.

Explanation
Implicit input of integer U.
õ

Generate an array of integers from 1 to U.
fj

Filter (f) primes.
w

Reverse.
æ_

Return the first element that returns a truthy value (in this case 1) when passed through a function that checks if ...
sø666

The integer converted to a string (s) contains (ø) 666.

Faster Alternative, 15 bytes
Again, seeing as there was originally a time-based bonus, here's an alternative, and much faster, solution which I can't seem to golf any further.
U-@j *U´sø666}a

Test it

Perl 5, 47 bytes
46 bytes of code + 1 for -p
{$f=0|sqrt;1while$_%$f--;/666/*!$f||$_--*redo}

Try it online!

PowerShell, 128 bytes
param($n)function f($a){for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}}for(){if($n-match666-and($n-eq(f $n))){$n;exit}$n--}

Try it online!
PowerShell doesn't have any prime factorization built-ins, so this borrows code from my answer on Prime Factors Buddies.
We take input $n, then declare a new function f that calculates out the factors of input $a. If the input $a is prime, then this will return just $a.
The main part of the program is the infinite for() loop. Inside the loop, we check if $n -matches against 666 and whether $n is prime (i.e., $n matches all of the factors of $n). If it is, we place $n on the pipeline and exit, with implicit output. Otherwise, we decrement $n-- and continue the loop.

Trimmed mine version down and just managed to hit half your byte count :D  - https://codegolf.stackexchange.com/a/140539/571

Python 2, 77 76 bytes
Edit: -1 byte thanks to @Mr.Xcoder
Slow running time, runs in O(n^2)
lambda x:max(q for q in range(x+1)if"666"in`q`*all(q%t for t in range(2,q)))

Try it online!
Another 76 bytes solution
lambda x:max(q*("666"in`q`*all(q%t for t in range(2,q)))for q in range(x+1))

Try it online!
With SymPy 73 bytes
lambda x:max(q for q in primerange(0,x+1)if"666"in`q`)
from sympy import*

Try it online!

76 bytes: lambda x:max(q for q in range(x+1)if"666"in`q`*all(q%t for t in range(2,q))) - use max() instead of [][-1]

Bash + bsd-games package, 33

2 bytes saved thanks to @FedericoPoloni.

primes 2 $[$1+1]|grep 666|tail -1

Try it online.

You can save 1 byte if you replace the last two commands with tail -n1.

@FedericoPoloni duh - can't believe I forgot tail here.  In fact tail -1 is even 1 less.

PowerShell, 71 69 64 bytes
param($s)for(;$s-notmatch666-or(2..($s/2)|?{!($s%$_)});$s--){}$s

Try it online!

328765 takes ~30 seconds on my machine, but times out the 60 second limit on Tio.run.
678987 takes ~1.5 minutes.
969696 takes ~4.5 minutes.

Clever way of doing the factors.

MATL, 16 bytes
ZqP"@V'666'Xf?@.

Try it at MATL Online
Explanation
         Implicitly grab input (n)
Zq       Compute the primes up to n (output is in increasing order)
P        Flip the array (so larger primes come first)
"        For each prime
  @V     Convert it to a string
  '666'  Push the string literal '666' to the stack
  Xf     Find the location of '666' in the prime
  ?      If it was present...
    @.   Push it to the stack and break
         Implicitly display the stack contents

C++ 389 bytes
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>
using namespace boost::random;typedef boost::multiprecision::cpp_int Z;int main(int,char**v){mt19937 m(clock());independent_bits_engine<mt11213b,256,Z>g(m);Z n{v[1]},p;while(p++<=n)if(miller_rabin_test(p,25,g)&&p.convert_to<std::string>().find( "666" )!=-1)std::cout<<p<<" ";}

This is a full program!
You'll need Boost to compile it. (Or copy and paste into your favorite online C++ shell.)
Run it from the command-line giving n as argument.
Ungolfed:
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>
using namespace boost::random;

typedef boost::multiprecision::cpp_int integer;

int main( int argc, char** argv )
{
  mt19937 mt( clock() );
  independent_bits_engine <mt11213b, 256, integer> rng( mt );

  integer input {argv[ 1 ]};
  integer possible;

  while (possible++ <= input)
    if (
      // is_prime( possible )
      miller_rabin_test( possible, 25, rng )
    &&
      // possible has "666" in it
      (possible.convert_to <std::string> ().find( "666" ) != std::string::npos))

    std::cout << possible << " ";
}

Shortcuts were made in terms of random number testing. The original code started testing possible primes at 6661 and incremented by two. You'll also get a compiler warning because of that (-1) there instead of npos.
Still, this runs pretty quickly. It only took about 40 seconds to find all 214 satan primes under 1,000,000 on my old AMD Sempron 130.
:^D

Stax, 10 bytes
ü>:Ñb/VP6─

Run and debug it
Explanation (unpacked):
^w:pc$666$#! Full program, implicit input-parsing
^            Increment input
 w           do-while:
  :p           Previous prime
    c$         Copy and stringify
      666$     Push "666"
          #    Number of occurences
           !   Logical not
             Implicit output

Nice program.  Thanks for trying stax.  FYI, it's also possible to do multiple cases by using the "Separator" option like this

@recursive ah, thx

R, 57 bytes
(a=conf.design::primes(scan():1))[which(grepl(666,a))[1]]

-42 bytes from Dominic Van Essen's enormous golf.
uses grepl to coerce values to string(since 666 cannot be considered a regex) and check for truthy values.
Runs through the array in reverse to save 2 bytes.
R + conf.design, 81 78 99 bytes
library(conf.design);function(n){a=primes(1:n)
a[max(which(grepl("666",as.character(a),fixed=T)))]}

Try it on rdrr.io!
My first R solution.
+21 bytes after including library name.
A simple filter. grepl returns true at indices with 666, which returns the truthy indices, and max gets the required index of the prime.

Congratulations on your first R golf!  The good news: you can make the code shorter (58 bytes) like this function(n)(a=primes(1:n))[max(which(grepl("666",a,f=T)))], and then even shorter (52 bytes) by using scan() for input like this (a=primes(1:scan()))[max(which(grepl("666",a,f=T)))] (but I don't know how to make scan() work correctly on rdrr.io...

The bad news is that the current consensus (that I only recently learned of) is that we need to include either the code to load the library (library(conf.design)) or to specify the library for the function (conf.design::primes) in the byte-count, which brings the shortest version back up to 65 bytes: (a=conf.design::primes(1:scan()))[max(which(grepl("666",a,f=T)))].

Actually, 57 bytes: (a=conf.design::primes(scan():1))[which(grepl(666,a))[1]], by letting grepl coerce both arguments to character, leaving-out the fixed=TRUE which isn't required here (because 666 can't be mistaken for a regex), and running-through the series in reverse order, so we can take the first ([1]) element instead of the max().

I've edited the answer to include the right solution.

56 bytes using match(T,x) (that always returns the first matching element) instead of which(x)[1]: (a=conf.design::primes(scan():1))[match(T,grepl(666,a))]

Python 3, 85 83 80 bytes
Halvard's is 4 bytes shorter because it's done in Python 2.
lambda k:max(x for x in range(k+1)if"666"in str(x)*all(x%i for i in range(2,x)))

Try it online!
Give it some time, it's extremely slow because of its O(n^2) complexity.

JavaScript (ES6), 55 54 bytes
-1 byte thanks to @ThePirateBay.
f=n=>/666/.test(d=n)&eval("while(n%--d);d<2")?n:f(n-1)

Very slow with large inputs. Primality test adapted from this code golf answer.
Timings

Input 10000 took 10 seconds
Input 328765 took 3 minutes
Input 678987 took 9 minutes
Input 969696 took 16 minutes

Tests
Some of these will hang your browser for several minutes.

f=n=>/666/.test(d=n)&eval("while(n%--d);d<2")?n:f(n-1)

function test(n) {
  O.value="Working..."
  setTimeout(_=>{
    let t = Date.now()
    O.value=`f(${n}) = ${f(n)} in ${(Date.now()-t)/1000}s`
  }, 10)
}
Tests

<button onclick="test(6662)">6662</button>
<button onclick="test(10000)">10000</button>
<button onclick="test(328765)">328765</button>
<button onclick="test(678987)">678987</button>
<button onclick="test(969696)">6662</button>

Result

<input id=O type=text size=25 readonly>

Faster Version, 56 bytes
Completes each test case in under a second.

f=n=>/666/.test(n)&&eval("for(d=2;n%d++;);d>n")?n:f(n-1)

;[6662, 10000, 328765, 678987, 969696].forEach(n=>console.log(`f(${n}) -> ${f(n)}`))

You should never do that. This is code golf and the performance is totally irrelevant. I strongly suggest rolling back to your previous 55 byte answer. Also, you can reduce it to 54 bytes by replacing d==1 with d<2 since n>6661.

52 bytes: f=n=>/666/.test(n)&(g=d=>n%--d?g(d):d<2)(n)?n:f(n-1) but will throw a recursion error for larger numbers.

Ruby, 67, 66, 58, 56 bytes
Includes +7 bytes for -rprime
->z{z.downto(1).find{|x|/666/=~x.to_s&&x.prime?}}

It's pretty fast, computing values up to ~2^52 in about a second and 2^64 in under 5 minutes (2011 MBP, Ruby 2.3.1).

PHP, 148 bytes
<?php $p=[2];$s=[];for($i=3;$i<=$argv[1];$i++){foreach($p as $q)if($i%$q===0)continue 2;$p[]=$i;if(strpos($i,'666')!==false)$s[]=$i;}echo end($s);?>

Try it online!

Perl 6, 35 bytes
my&f={/666/&&.is-prime??$_!!f $_-1}

Try it online!
Straightforward recursive solution.

C# (.NET Core), 117 115 112 bytes
f=>{for(int i=f;i>1;i--){int p=1,j=2;while(j<i)if(i%j++<1)p=0;if(p>0&$"{i}".Contains("666"))return i;}return 0;}

Try it online!

2 bytes saved by removing unnecessary braces.
3 bytes saved by combining int declarations.

I'm sure this could be made shorter; maybe by recursively calling func f and removing the outer for-loop.
Recursive Approach, 85 bytes
i=>{int p=1,j=2;while(j<i)if(i%j++<1)p=0;return p>0&$"{i}".Contains("666")?i:f(--i);}

Try it online!
I'm unsure how well this approach fits within the bounds of code-golf due to having to set the Func<int,int> f = null first, and that f is called again, but not counted towards the bytes. Any clarification would be appreciated.

05AB1E, 9 bytes
ÅPR.Δ666å

Try it online. (No test suite with all test cases, because it's a bit too slow.)
Explanation:
ÅP         # Push a list of primes below or equal to the (implicit) input-integer
  R        # Reverse this list
   .Δ      # Find the first value which is truthy for:
     666å  #  Check whether it contains "666" as substring
           # (after which the found result is output implicitly)

The 666 can alternatively be Ž2ć (compressed 666) or Ƶé· (compressed 333 and then doubled).

Java 8, 77 bytes
n->{for(int i=++n;i>1|!(n+"").contains("666");)for(i=--n;n%--i>0;);return n;}

Try it online.
Explanation:
n->{               // Method with integer as both parameter and return-type
  for(int i=++n;   //  Increase the input by 1
                   //  Set `i` to this input+1 (setting `i` to anything above 1 is fine)
      i>1          //  Continue looping as long as `i` is not 0 nor 1
      |!(n+"").contains("666");)
                   //  or if `n` as String does not contain "666" as substring:
    for(i=--n;     //   Decrease `n` by 1 first
                   //   And then set `i` to this new `n`
        n%--i      //   Decrease `i` by 1 before every iteration
             >0;); //   And continue looping as long as `n` does NOT evenly divide `i`
  return n;}       //  After both loops, return the modified `n` as result

If for(i=n;n%--i>0;); results in \$i<2\$, it means \$n\$ is a prime number (note: this prime checker only works for \$n\geq2\$, which is fine in this case).

Husk, 12 bytes
ḟo`€d666dfṗṫ

Try it online!