text:
Is it a new highscore?
Challenge:
In the language of your choice, write a program that generates a leaderboard with random scores and outputs it, then take a new score as input and check if it can be placed in the leaderboard, and output which place it is in.
Specifications:

You must generate a list of 50 "random" scores, in descending order and output it
The "random" scores will range from 0 to 255
If 2 scores are the same, it doesn't matter which is placed first in the descending order
If the input score isn't higher than any of the scores in the list, output 0 or a falsy statement. (the input will be 0 to 255, no need to check)
If the score IS higher than a score in the list, output the position it would take in the leaderboards.
Generate and output the leaderboards/list first in descending order, before taking input.

Example I/O:
Random list:  (the three dots are so I don't have to add 50 line text here. You should output each score. 12 is the 50th place)
201
192
178
174
...
...
12

Input:
180

Output:
3

(because this score would place no.3 in the leaderboards)
Input 2:
7

Output 2:
0

(because it is lower than everything on the leaderboard)
This is a code-golf so shortest code wins.

What if I have score list 10 9 9 7 5 and I get an input of 9?

@EriktheOutgolfer If 2 scores are the same, it doesnt matter which is placed first in the descending order - I assume that applies for that case too.

@Mr.Xcoder I think "the descending order" refers to the first 50 scores.

@Mr.Xcoder Indeed. Assuming "10" is first, your input can have output of 2 or 3, whatever fits your code best.

I thought the output could be 2, 3 or 4 in that case?

Can I output as a list of [[highscores], input's position]?

@BusinessCat Generate and output the leaderboards/list first in descending order, before taking input.

@EriktheOutgolfer My bad, you are correct.

Does random generation need to be uniform?

@Downgoat if I understand the question correctly, then no, that's why there are quotation marks on random, the numbers produced are pseudorandom.

Python 2, 102 bytes
from random import*
lambda n,l=[randint(0,255)for i in[0]*50]:(l,[sorted(l+[n]).index(n),0][n>max(l)])

Try it online!

Since you're already importing random, you can save 6 bytes by doing sample(range(256)*50,50) instead of [randint(0,255)for i in[0]*50]

This does not follow the specification bullet point: "Generate and output the leaderboards/list first in descending order, before taking input." - it'll have to be a full program to achieve this.

Python 3, 125 128 127 126 125 119 115 bytes
from random import*;x=sorted(choices(range(256),k=50));print(x[::-1]);print((sum(map(int(input()).__lt__,x))+1)%51)

Could probably be golfed quite a bit
Edit: Changed from sample to choices, as sample does not allow repetition. Pointed out by @Arnold Palmer
-2 bytes, thanks to @Arnold Palmer
-4 bytes, thanks to @Jonathan Allan
Try it online!

Here's a 118 byte Python 2 one I just did that's a bit smaller.  A straight conversion to Python 3 is larger than yours, but this shaves off 7 bytes.  Also, sample forces unique elements, so your leaderboard will never have duplicates, which I believe is incorrect.  For +3 you could just do sample(range(256)*50,50), but that's still technically not random.

You can save a byte if you do [0,sum(a>i for a in x)+1][i>x[0]] instead of [sum(a>i for a in x)+1,0][i<=x[0]]

I don't think you need the * in print(*x[::-1]) since generally printing the actual list of numbers is fine.

Nice work. You can save four bytes by using a map like so (avoiding creating i and using the for with a little overhead)

R, 69 bytes
n=scan();cat(r<-sort(sample(256,50,T)-1,T));`if`(any(r<n),sum(r>n),0)

reads n from STDIN; prints the list to STDOUT, and returns the index or 0.
Try it online!
Cleaner output format

Jelly, 18 bytes
⁹ẋ50ḶX€ṢṚṄ€>ƓS‘%51

Try it online!
-3 thanks to Jonathan Allan.
Now with interactive I/O!
Full program. First 50 lines are the scores, last line is the index.

I see, makes sense now!

How about ...Ṅ€>ƓS‘%51 for 3 less?

@JonathanAllan Nice.

Javascript, 155 148 134 115 101 bytes
Not very short, but:
l=[...Array(50)].map(x=>Math.random()*256|0).sort((a,b)=>b-a);console.log(l);f=x=>l.findIndex(v=>x>v)

Returns position when higher than at least one score. Otherwise -1.
Edit: apparently you don't have to output scores line by line. So shorter now.

l=[...Array(50)].map(x=>Math.random()*256|0).sort((a,b)=>b-a);console.log(l);f=x=>l.findIndex(v=>x>v)

console.log(f(200))
console.log(f(60))
console.log(f(30))
console.log(f(2))

14 bytes saved by @Downgoat

Array(50).fill(0).map(x=>Math.round(Math.random()*256)) is one byte shorter than Array.from({length:50},x=>Math.floor(Math.random()*256)).

Even shorter: [...Array(50)].map(x=>Math.random()*256|0)

@Downgoat I keep forgetting that spread operator... thanks!

Charcoal, 48 bytes
ＡＥ⁵⁰‽²⁵⁶ηＦ⁵⁰«⊞υ⌈ηＡ§η⌕η⌈η⁰»ＩυＤ⎚ＮθＩ﹪⁺¹Ｌ⪫Ｅυ× ›ιθω⁵¹

Try it online! Link is to verbose version of code. There's no Sort function in Charcoal, so I loop 50 times extracting the highest remaining element and then setting it to zero each time, using the ambiguous AssignAtIndex command. There is an experimental Reduce function in Charcoal but I'm too wary of it so I'm taking the length of a string instead. Unfortunately this gives me a 0-indexed answer to I have to add 1 modulo 51 to give the desired answer. At least generating the 50 random numbers was easy.

well there's always ▷s⟦<args>⟧/▷s<arg> (sorted, sort is just sort), verbose is evalvar("s", [args])

@ASCII-only I tried Assign(Reverse(evalvar("s", Map(50, Random(256)))), u); but it doesn't seem to work for some reason: Try it online!

:/ this is because Clear clears all variables as well, oops

@ASCII-only Strange, because it seems to work with the "long" version...

Oh that's because it's pushing to the hidden variable u which is not reset, I've changed it anyway so it will now be consistent after Dennis pulls Charcoal.

Ah, so Assign doesn't work because u gets reset to its original empty list, but Push works because I'm changing the list that u gets reset to?

Let us continue this discussion in chat.

30 bytes

TXR Lisp, 78 76 bytes
(opip(pos-if(op > @@1)(prinl[sort[(gun(rand 256))0..50]>]))(if @1(+ 1 @1)0))

Run:
1> (opip(pos-if(op > @@1)(prinl[sort[(gun(rand 256))0..50]>]))(if @1(+ 1 @1)0))
#<intrinsic fun: 0 param + variadic>
2> [*1 3]
(247 243 238 237 234 209 204 202 196 193 183 181 179 177 174 174
 164 159 156 155 143 141 138 134 134 132 131 117 105 98 89 88
 82 77 75 66 65 64 55 52 46 34 32 28 28 26 24 21 18 5)
0
3> [*1 3]
(252 250 241 236 234 229 228 219 210 206 205 204 193 188 184 168
 166 164 163 160 158 158 148 138 137 130 123 118 111 103 97 93
 92 85 81 73 69 60 60 53 52 44 38 31 19 16 15 12 10 1)
50
4> [*1 245]
(251 248 244 238 237 228 225 223 222 220 219 216 208 197 196 192
 191 176 159 157 155 149 140 138 121 119 115 113 108 106 105 101
 87 82 79 69 67 59 54 42 40 38 34 19 18 12 11 9 4 4)
3
5> [*1 255]
(255 241 228 228 226 224 222 222 217 214 211 197 197 193 191 185
 176 175 173 166 162 142 141 139 132 132 122 122 110 110 109 106
 104 83 82 81 81 79 74 69 69 65 61 60 59 51 41 37 25 14)
2
6> [*1 255]
(248 244 240 234 231 220 214 211 207 206 205 200 197 188 187 184
 183 182 173 153 150 149 144 130 127 126 122 113 109 98 94 89
 74 66 60 60 58 54 54 51 49 45 21 15 12 12 10 8 7 3)
1

Mathematica, 105 bytes
(P=Position;Print[If[(d=Min@Nearest[s=Reverse@Sort@RandomSample[Range@251-1,50],#])<#,s~P~d,s~P~d+1],s])&

Try it online!

Ruby, 78 bytes
puts h=[*0..255].sample(50).sort.reverse
s=gets.to_i
p (h.index{|i|i<s}||-1)+1

Gaia, 17 bytes
{256ṛ(}₅₀]ȯv:q<∆q

There was a small bug with the random function, so this won't work quite properly on the version on TIO, but will work locally.
Try it online!
Exaplanation
{256ṛ(}            Get a random integer from 1 to 256 and decrement it.
       ₅₀          Do that 50 times.
         ]         Collect the results in a list.
          ȯv       Sort in descending order.
            :q     Copy and print.
              <∆   Find the index of the first score that is less than the input (input
                   won't be read until this point).
                q  Print that index.

Haskell, 176 bytes
Haskell is certainly the wrong tool for this job, far too long..
(sequence(randomRIO(0,255)<$[1..50])::IO[Int])>>=g.sort
import System.Random
import Data.List
g l=mapM_ print(reverse l)>>getLine>>=print.(#l).read
x#l=1+length(takeWhile(<x)l)

Try it online!

Bash + GNU utilities, 76
shuf -i0-255 -n50|sort -nr|tee s
sed 1i$1i s|sort -nr|sed -n /i/=|dc -e?51%p

Try it online.
Explanation
shuf -i0-255 -n50                            # generate random leaderboard
                 |sort -nr                   # sort it in descending numerical order
                          |tee s             # output and save to file s
sed 1i$1i s                                  # insert new score with an "i" suffix
           |sort -nr                         # sort again
                    |sed -n /i/=             # output line number of line containing "i"
                                |dc -e?51%p  # mod 51 of line number

Perl 5, 77 + 1 (-p) = 78 bytes
@a=sort{$b<=>$a}map{int rand 255}1..50;say"@a";1while$a[$i++]>$_;$_=$i<51&&$i

Try it online!
Outputs the scoreboard space separated on the first line.  Outputs the position for the new input on the second line.  Second output is blank (falsy) if the new score isn't high enough to make the leaderboard.

I don't think this meets the spec of taking input after printing the list (it also doesn't terminate but I'm not sure that's actually an issue)

Röda, 112 bytes
{a=[seq(1,50)|[-abs(randomInteger()%256)]for _|sort]a|print-_
parseInteger _|indexOf-_,[sort(a+-_1)]|[(_+1)%51]}

Try it online!
This reads the input from the input stream as a string (like if it was stdin). The answer could obviously be shorter if I can suppose that the input is a number object, as the parseInteger _ call would not be needed. I'm not sure if I can do that.

MATL, 18 bytes
Thanks to Jonathan Allan for removing 1 byte and for a correction!
8W50&YrqSPtD<sQ51\

Example run
The leaderboard is shown as a line of numbers separated by spaces. The gif only shows the first few, to keep image size reasonable.

Explanation
8W   % Push 2 raised to 8, that is, 256
50   % Push 50
&Yr  % Random vector of 50 integers from 1 to 256, independently uniformly distributed
q    % Subtract 1 to each result. This makes the integers go from 0 to 255
SP   % Sort, reverse. This sorts in descending order
tD   % Duplicate and immediately display
<    % Implicit input. Is it less than each entry in the sorted random vector?
s    % Sum. This counts how many entries are less than the input
Q    % Add 1
51\  % Modulo 51. Implicitly display

Wouldn't SP sort and reverse?

Also wont this output 51 when it should output 0?

... I think it should be 18?

@JonathanAllan You're right on both, thanks! I hadn't seen the 0 output requirement

Java 8, 208 + 19 = 227 bytes
It's golfs like these that make me question my choice of language.
The I/O order specification prohibits the use of lambda parameters and return values for I/O, but I use a lambda anyway to avoid the main class boilerplate. The lambda can be assigned to Runnable.
Byte count includes lambda and required import.
import java.util.*;

()->{int n,p=0;List<Integer>l=new Stack();for(;p++<50;l.sort((a,b)->b-a))l.add(new Random().nextInt(256));System.out.print(l);n=new Scanner(System.in).nextInt();for(int o:l)if(n>o)p--;System.out.print(p%51);}

Ungolfed lambda
() -> {
    int n, p = 0;
    List<Integer> l = new Stack();
    for (; p++ < 50; l.sort((a, b) -> b - a))
        l.add(new Random().nextInt(256));
    System.out.print(l);
    n = new Scanner(System.in).nextInt();
    for (int o : l)
        if (n > o)
            p--;
    System.out.print(p % 51);
}

It's pretty readable once ungolfed. My favorite part about this solution is that it sorts the scoreboard 50 times (whenever a new score is generated) in order to save one byte. This results in a noticeable delay while the board is generated.
p is incremented to 51 as the scoreboard is populated, and then is decremented to the input score's ranking. The remainder by 51 is taken so that rank 51 is displayed as 0.
Since each initial score is produced by a newly-seeded generator, the scores probably don't have the usual guarantees of randomness. But they seem random enough to me.

Ly, 58 bytes
(50)[>0(255)?<1-]>ar&s&ulrns>1<[L[>"\n"ou;]ppl>1+<]"\n"o0u

Try it online!
Outputs a space-separated list of scores, then the position of the given input after a newline.
Explanation:
(50)[>0(255)?<1-]>    # simple loop to create list of 50 scores
ar&s&ulr              # arrange the list, reverse it, print it, then reverse it back
ns                    # take input and save it
>1<                   # prepare counter
[                     # while the stack is not empty
    L[>"\n"ou;]       # check if the value is lower than the input, if so, output a newline and the counter, then terminate
    ppl>1+<           # otherwise, pop a value off the stack and increase the counter
]
"\n"o0u               # output a newline and 0 if we finished the loop without terminating

PHP, 119 bytes
<?php while($c++<50)$l[]=rand(0,255);rsort($l);foreach($l as$s)echo"$s ";for($i=fgets(STDIN);$i<$l[++$p-1];);echo$p%51;

Try it online!
Please note, when trying it online, you are required to give the input before you have seen the starting leaderboard, but this is not how it actually runs from a CLI: the leaderboard is printed first and the program waits for the user input.
Explanation
<?php

Generate 50 random numbers and store in the leaderboard, $l.
while ($c++ < 50) $l[] = rand(0, 255);

Sort them in descending order.
rsort($l);

Print them out space-separated.
foreach ($l as $s) echo "$s ";

A loop, comparing the user input score $i  with the score in position $p in the leaderboard.
for (

Before we start, get the user input.
        $i = fgets(STDIN);

We loop from the top of the board ($l[0]) and keep looping for as long as $i is less than the score in that position.
$p is initially undeclared so we increment it before each comparison (so it starts as an integer), but have to subtract 1 for a 0 start.
        $i < $l[++$p - 1];
);

Print the resulting position. If $i is less than any score on the leaderboard $p will equal 51. Using modulus 51, results in 51 becoming 0, but the other positions remaining unchanged,
echo $p % 51;


text:
What's my PPCG ID?
Challenge
Given the name of a PPCG member, output their PPCG ID number. If the user does not exist, you may report an error or return any non-positive number. If there are multiple members with this name, you may choose to output only one ID or all of them.
Test Cases

"musicman523" -> 69054
"Dennis" -> 12012
"xnor" -> 20260
"Leaky Nun" -> 48934
"fəˈnɛtɪk" -> 64505
"Jörg Hülsermann" -> 59107
"Community" -> -1
"Any user that does not exist" -> 0
"Alex" -> 69198 (this is one possible result)
"Leaky N" -> 0
"Jorge" -> 3716

Sandbox

If there are multiple users with the same name, can we output any one of them?

@Okx Yes, any of them is fine

Related

Recommended test case: "Leaky N". Should return 0.

Can our program result in undefined behaviour for inexistent users (mine prints 48934, for example for a non-existing user)? I think this should be allowed, since errors are.

@Mr.Xcoder The question states that If the user does not exist, you may report an error or return 0. I think you have your answer.

@Okx No, I don't. I am asking the OP if this behaviour is allowed. If it is not, I will delete or fix my answer.

@Mr.Xcoder Sorry, how does that not answer your question?

@Okx Sorry, can you please not be so toxic here? I see your point, but you could be a little nicer about it.

@OliverNi Toxic? How?

@Okx He is asking a valid question to the OP and you are shooting him down immediately. Let the OP answer.

@Mr.Xcoder You can do anything besides return a positive integer. This includes (but is not limited to) throwing an exception, returning 0, returning a negative number, etc.

@musicman I fixed my answer.

I wonder if this could be answered with a Stack Exchange Data Explorer query...

@StevenVascellaro Done and done.

Recommended test case: "Jorge". Should return 3716 (as of right now)

Stack Exchange Data Explorer, 56 54 53 51 46 bytes
-1 byte thanks to Hyper Neutrino. -5 bytes thanks to Giacomo Garabello.
SELECT ID FROM USERS WHERE##S##=DISPLAYNAME--S

Try it online!
Not sure if this is completely valid but... Input must be surrounded in single quotes '.
Also, I still don't get why SQL programmers like to shout but it's apparently good practise so... SELECT EVERYTHING FROM EVERYTHING WHERE EVERYTHING LIKE EVERYTHING!
Explanation
LET ME EXPLAIN.
SELECT ID FROM USERS WHERE##S##=DISPLAYNAME--S

                                           --S  -- DECLARE AN INPUT PARAMETER NAMED S
SELECT                                          -- FIND...
       ID                                       -- ID OF THE USERS...
          FROM USERS                            -- IN THE TABLE USERS...
                     WHERE                      -- THAT SATISFIES THE CONDITION...
                          ##S##=DISPLAYNAME     -- S EQUALS THE USERS' DISPLAY NAME

-2 BYTES BY REMOVING THE SPACES AROUND THE EQUALS SIGN

NINJA'D YOUR NINJA IN CHAT XD

-1 byte by reversing the order of operands around the equality operator

-1 byte: 1Id (the space is unnecessary)

Wait, is SQL's whitespace requirement the same as Python's? o0

Apparently so ¯\(ツ)/¯

Don't think it's quite fair to require the input include quotes. +2 bytes to add the quotes back into your answer: SELECT TOP 1ID FROM USERS WHERE'##S##'=DISPLAYNAME--S

It's accepted for Python to do it, so I don't see why ---SQL--- SEDE should be disallowed from using it.

+1 for the reference to SQL programmers liking to shout (and for a nice choice of language for your answer :)

why have you put the top 1 in this query? OP said "If there are multiple members with this name, you may choose to output only one ID or all of them"...

Ohh, I must've missed that. Thanks for spotting that!

i am stupid i searched something about stackexchange api and this was second in the results and i didnt see it

Seems to fail for every username?

@SteveFest Still works fine for me. Are you surrounding the input with single quotes?

No. I just typed SteveFest. I also tried your username and it fails too.

@SteveFest You should be doing it lol. The answer says so.

Oops, my fault.

Not sure if the Data Explorer has changed since this was written, but I don't think you need the --S at the end any more, it correctly prompts for the parameter with only the ##S##.

Python 3 + requests, 196 bytes
Thanks @Wondercricket for -6 bytes!
from requests import*
x=lambda s:all([print(a['user_id'])if s==a['display_name']else''for a in get('http://api.stackexchange.com/users?inname=%s&site=codegolf'%utils.quote(s)).json()['items']])and d

Uses Stack Exchange API. Fixed the Leaky N and Jorge errors.
If there are multiple users with the same name, it prints all of them, which is allowed.

It gives me gzipped data..

Fails on input Leaky N

@Okx Fixed. ---

Since you can "report an error or return 0" if the user does not exist, can't the last line be just print a['user_id'], which will throw a KeyError?

No, since Leaky N would return something.

@Dopapp Looking at the code, you see that it searches with the parameter inname. Thus, SE is only checking that it's in the name.

@Okx, oh yeah I see that now

You can take advantage of a module within request and replace s.replace(' ','%20') with utils.quote(s) for 173 bytes

fails for "Jorge"

@FelipeNardiBatista Fixed.

Python 2 + requests, 187 bytes
from requests import*
def f(x):t=get("http://api.stackexchange.com/users?inname="+utils.quote(x)+"&site=codegolf").json()["items"];print[k['user_id']for k in t if k['display_name']==x][0]

Returns the user ID if a single user exists, the first user which matches the requirements if more exist, and reports an error otherwise.

You can remove /2.2 from the API-url.

@KevinCruijssen Thanks a lot

Hint: Do not try to run it with fəˈnɛtɪk, use \u{...} instead, because Python does not tolerate non-ASCII

Python 2, anyways.

Mentioned this as a comment to Oliver's answer, but you can shed 6 bytes by replacing s.replace(' ','%20') with utils.quote(s); utils being a module within requests

@Wondercricket Thanks a lot!

fails for "Jorge"

Ok, hopefully all the issues are fixed now.

JavaScript, 155 149 142 135 bytes
i=>fetch("//api.stackexchange.com/users?site=codegolf&inname="+i).then(r=>r.json()).then(r=>r.items.find(u=>u.display_name==i).user_id)

f=i=>fetch("//api.stackexchange.com/users?site=codegolf&inname="+i).then(r=>r.json()).then(r=>r.items.find(u=>u.display_name==i).user_id)
<input onchange="f(this.value).then(console.log)">
Fill input and press Enter

Does it support special characters like in Jörg Hülsermann?

This returned 0 for Oliver :(

Save 7 bytes by replacing r=>r.items[0]).then(r with ({items:[r]}).  Destructuring assignment ftw!

You can use: i=>fetch('//api.stackexchange.com/users?site=codegolf&inname='+i).then(r=>r.json()).then(r=>r.items[0].user_id) as it'll return a promise error if it failed. You can also just do i=>fetch('/users?site=codegolf&inname='+i).then(r=>r.json()).then(r=>r.items[0].user_id) and say it needs to be run on the api domain

Version that fixes bug reported by @Oliver and saves 7 bytes: i=>fetch(\//api.stackexchange.com/users?site=codegolf&inname=`+i).then(r=>r.json()).then(r=>alert(r.items.find(u=>u.display_name==i).user_id))` - be careful of StackExchange's zero-width spaces when copy-pasting.

You can save a few bytes by just returning the Promise, rather than alerting the result from it.

@Downgoat how can I show the result of the promise?

@Uriel, call the function like so: f("Shaggy").then(console.log). See here for more on that consensus. (Note that your solution still fails on usernames containing special characters)

@Oliver WHAT another oliver???? THERE CAN BE ONLY ONE

@OliverNi you are Oliver Ni, he's Oliver

@OliverNi Ironically you were the reason Oliver used to return 0 :P Apparently "Oliver Ni" is a better match than "Oliver" when searching for "Oliver".

@Birjolaxew, it's because the default sort order for this query is by reputation descending which, as of this writing, places OliverNi at the top of the list.

@Shaggy would be .then(::console.log)

No need for the colons in this case, @Downgoat; give it a try in the consensus I linked to above.

@Shaggy not sure what you mean. Code would error without colons

@Downgoat: try it here

Python 2 + requests, 173 bytes
lambda s:[i['user_id']for i in get('http://api.stackexchange.com/users?inname=%s&site=codegolf'%utils.quote(s)).json()['items']if i['display_name']==s]
from requests import*

Sample run
>>> f=\
... lambda s:[i['user_id']for i in get('http://api.stackexchange.com/users?inname=%s&site=codegolf'%utils.quote(s)).json()['items']if i['display_name']==s]
>>> from requests import*
>>>
>>> tests = ['musicman523', 'Dennis', 'xnor', 'Leaky Nun', 'Community', 'Any user that does not exist', 'Alex', 'Leaky N', 'Jorge']
>>> for i in tests: print '%-30r -> %s'%(i, f(i))
...
'musicman523'                  -> [69054]
'Dennis'                       -> [12012, 13891, 14912, 24937]
'xnor'                         -> [20260]
'Leaky Nun'                    -> [48934]
'Community'                    -> [-1]
'Any user that does not exist' -> []
'Alex'                         -> [21536, 69198, 11192]
'Leaky N'                      -> []
'Jorge'                        -> [3716]

Fun fact: the result is sorted by reputation, highest first.

Fails on input Leaky N

Nice trick with %s.

@Okx Not for me, it doesn't. >>> f('Leaky N')\n48934

@totallyhuman It should return 0. Leaky N does not exist

@Okx Fixed. - -

s==t['display_name']and instead of t['display_name']==s and for -1 byte

Oh, love abusing Python's whitespace requirements. Thanks!

Oh, so is the import for requests not required?

@Okx Oh, my bad.

The OP replied: Your 147 byte approach is invalid.

Aw, maaan... ;-;

Fails for "Jorge"

@FelipeNardiBatista Fixed.

JavaScript, 128 119 bytes
-9 bytes thanks to Rogem.
n=>fetch("198.252.206.16/users?site=codegolf&inname="+n).then(r=>r.text()).then(t=>t.match(`\\/([^\\/]*)\\/`+n+`"`)[1])

Think you'd save some bytes with the IPv4 address. (198.252.206.16 instead of api.stackexchange.com)

APL (Dyalog Unicode), 169 bytes
a←⍞
y←(⎕JSON((⎕SE.SALT.New'HttpCommand').Get'https://api.stackexchange.com/users?site=codegolf&inname=',('\s+'⎕R'\%20')a).Data).items
{a≡1⊃y.display_name:y.user_id ⋄ 0}1

This took forever to figure out, lol.
Thanks to @Adám for saving me a lot of time, and a lot of bytes on the HTTP request.
Explanation
a←⍞                                 ⍝ Store string input
y←        ('\s+'⎕R'\%20')a          ⍝ Convert spaces to '%20' for query
  (⎕JSON((⎕SE.SALT.New'HttpCommand').Get'https://api.stackexchange.com/users?site=codegolf&inname=',).Data).items
                                    ⍝ Get and parse JSON from API call using ⎕SE (session namespace)
 a≡⊃y.display_name                  ⍝ Is the input equal to the unwrapped user id?
                                    ⍝ (display name comes as an array of strings)
{                  :y.user_id ⋄ 0}  ⍝ If so, print the user id
                                    ⍝ Else print zero
                                    ⍝ Call function with placeholder arg 1

This can be golfed a lot.

@Adám curl again, I suppose.

Not sure, as this one returns a compressed result, but you even have spaces around ⋄.

JavaScript (ES6) + HTML, 154 152 151 202 179 161 145 bytes
Sacrificed a few bytes to handle special characters.
Needs to be run under the api.stackexchange.com domain. Returns a Promise containing the ID or Throws an error in the Promise if the username can't be found.
s=>fetch(`/users?site=codegolf&inname=`+s).then(r=>r.json()).then(j=>j.items.find(i=>(o.innerHTML=i.display_name,o.innerText==s)).user_id)

<a id=o

Note: This solution was developed independently of Uriel's and its comments; if Uriel decides to use the find method, I'm happy to roll back to my longer, recursive version.

I've created a meta discussion on requiring a certain execution domain, since that does save quite a few bytes.

@Downvoter, please have the decency to leave a comment.

@Shaggy I would assume for the same reason as that meta discussion was started.

Downvoter, if you disagree with an established consensus (as @Rogem suggests), please downvote the relevant meta post rather than solutions that adhere to that consensus.

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:
Become the Hydra Slayer
You are the best and most famous hero of the area.  Lately there have been rumors that a Hydra has been hanging out in a nearby ravine. Being the brave and virtuous hero that you are you figure you'll go check it out sometime later today.
The problem with hydrae is that every time you try to cut off their heads some new ones grow back.  Luckily for you you have swords that can cut off multiple heads at once.  But there's a catch, if the hydra has less heads than your sword cuts, you wont be able to attack the hydra.  When the hydra has exactly zero heads, you have killed it.
There is also a special sword called The Bisector that will cut off half of the Hydra's heads, but only if the number of heads is even.  The Bisector cannot be used at all when the number of heads is odd.  This is different from cutting off zero heads.
So you have decided you will write a computer program to figure out the best way to slay the hydra.
Task
You will be given as input

the number of heads the Hydra starts with
the number of heads the Hydra regrows each turn
a list of swords available for use each (each either is a bisector or cuts a fixed number of heads each turn)

You should output a list of moves that will kill the hydra in the least number of turns possible.  If there is no way to kill the hydra you must output some other value indicating so (and empty list is fine if your language is strongly typed).  If there are multiple optimal ways to kill the hydra you may output any one of them or all of them.
This is a code-golf question so answers will be scored in bytes, with fewer bytes being better.
Test Cases
More available upon request
5 heads, 9 each turn,  [-1,-2,-5] -> [-5]
12 heads, 1 each turn, [/2,-1] -> No solution
8 heads, 2 each turn,  [-9, -1] -> [-1,-9]
3 heads, 23 each turn, [/2,-1,-26] -> [-1,-1,-26,-26,-26,-26,-26,-26,-26,-26]
16 heads, 1 each turn, [/2, 4, 2] -> [/2,-4,/2,-4]

This question is a simplified version of the main mechanic of HydraSlayer. If you like this type of puzzle I recommend checking it out, its pretty fun.  I do not have any affiliation with the game.

The number of heads grown each turn is constant, yes? Not dependent on the number of heads cut off?

@KSmarts That's correct.

If the bisector only works if the heads are even does that mean it does nothing if they are odd? Solution to @ThePirateBay would then be [/2,-26]

@dj0wns The Bisector cannot be used when they are odd.

@Nnnes That seems to be correct, incidently [/2, -2, /2, -2, -4] also works.

@WheatWizard I missed adding a head after the second /2, so it should be [/2,-4,/2,-4]

@Nnnes Ok fixed.

JavaScript, 230 223 bytes
f=(h,t,s)=>{m=h-Math.min(...s),d=1,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>!(a=w?h+w:h/2)?d=w:!(a%1)&a>0&a<m&!f[a+=t]?f[q.push([...p,w],a),a]=1:0);d<1?(q=[],p).push(d):0}return d<1?p:[]}

_=_=>f=(h,t,s)=>{m=h-Math.min(...s),d=1,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>!(a=w?h+w:h/2)?d=w:!(a%1)&a>0&a<m&!f[a+=t]?f[q.push([...p,w],a),a]=1:0);d<1?(q=[],p).push(d):0}return d<1?p:[]}

console.log(`[${_()(5, 9,  [-1,-2,-5])}]`);
console.log(`[${_()(12, 1, [0,-1])}]`);
console.log(`[${_()(8, 2,  [-9,-1])}]`);
console.log(`[${_()(1, 2,  [0,-4])}]`);
console.log(`[${_()(3, 2,  [0,-4,-1])}]`);
console.log(`[${_()(3, 4,  [0,-4,-1])}]`);
console.log(`[${_()(3, 23, [0,-1,-26])}]`);
console.log(`[${_()(16, 1, [0,-4,-2])}]`);

Ungolfed version:
f=(heads,turn,swords)=>{
  max=heads-Math.min(...swords);

  found=1;
  flags=[];
  queue=[];
  swords.map(a=>queue.push([],heads));

  while(queue.length){
    path=queue.shift();
    heads=queue.shift();

    swords.map(sword=>{
      after=sword?heads+sword:heads/2;

      if(!after){
        found=sword;
      }else if(!(after%1)&after>0&after<max&!flags[after+=turn]){
        flags[after]=1;
        queue.push([...path,sword],after);
      }
    });

    if(found<1){
      path.push(found);
      break;
    }
  }

  return found<1?path:[];
}

The bisector is represented as 0.

Python3, 197 bytes:
def f(h,H,s):
 q=[(h,[])]
 while q:
  h,m=q.pop(0)
  if 0==h:return m
  if m:h+=H
  for S in s:
   if((S==0.5 and 0==h%2)or(S!=0.5 and h>=abs(S)))and(h,S)not in m:q+=[([h/2,h+S][S!=0.5],m+[(h,S)])]

Try it online!

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


text:
prepend,append-Sequence
Task
The prepend,append-Sequence is defined recursively, like this

a(1) = 1
a(n) = a(n-1).n  , if n is even
a(n) = n.a(n-1)  , if n is odd

where the . represents an integer concatenation.
So the first few terms are: 1,12,312,3124,53124,531246,7531246,... This is A053064.
Your task is, given an integer a > 0 to return n, such that the nth element in the prepend,append-Sequence is equal to a and if no such n exists return 0, a negative number or error out etc.
Rules

Input can be taken as an integer, string, list of characters/digits etc.
Output can be printed to STDOUT or returned (integer, string etc. is fine)
On invalid input & in the case no such n exists your program may do anything but return a positive integer (eg. loop forever, return 0 etc.)
You may choose to use 0-indexing, but then the output in case no n exists cannot be 0

Test cases
1 -> 1
12 -> 2
21 -> 0
123 -> 0
312 -> 3
213 -> 0
211917151311975312468101214161820 -> 21
2119171513119753102468101214161820 -> 0
333129272523211917151311975312468101214161820222426283031 -> 0
999795939189878583817977757371696765636159575553514947454341393735333129272523211917151311975312468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698100 -> 100

More formal: a(n-1)*(int(log(n))+1)+n and n*(int(log(n))+1)+a(n-1)?

@Mr.Xcoder I would call that less formal :P

@JonathanAllan That is already in the question for ~10 minutes.

I suggest allowing errors for invalid inputs.

I suggest allowing undefined behaviour for invalid inputs.

Can we take input as a list of digits?

@Okx Yes, that's mentioned in the question.

C# (.NET Core), 83, 80, 60 59 bytes
n=>{int i=0;for(var t="";t!=n;)t=++i%2<1?t+i:i+t;return i;}

Try it online!
Takes the input as a string into a lambda function. 1-indexed. Returns the index of the value for truthy, or infitnitely loops for a "falsey"

Python 2, 63 bytes
-1 byte thanks to @EriktheOutgolfer.
f=lambda x,i='1',j=2:i!=`x`and f(x,[i+`j`,`j`+i][j%2],j+1)or~-j

Try it online!
Python 2, 64 bytes
-18 bytes thanks to @officialaimm, because I didn't notice erroring out was allowed!
x,i,j=input(),'1',1
while i!=x:j+=1;i=[i+`j`,`j`+i][j%2]
print j

Try it online!
Python 2, 82 bytes (does not loop forever)
This one returns 0 for invalid inputs.
def f(n,t="",i=1):
 while len(t)<len(n):t=[t+`i`,`i`+t][i%2];i+=1
 print(n==t)*~-i

Try it online!

Ninja'd :D 65 bytes

@officialaimm Thanks a lot! I didn't notice erroring out / loop forever was allowed.

Save a byte with a lambda: f=lambda x,i='1',j=2:i!=`x`and f(x,[i+`j`,`j`+i][j%2],j+1)or~-j

@EriktheOutgolfer Wait, it throws recursion error for everything, although I set sys.setrecursionlimit(). Can you provide a tio?

@Mr.Xcoder Does it throw an error for x=1? Or x=12? I thought it only threw such an error for at least x=151311975312468101214 or something.

@EriktheOutgolfer It doesn't work for anything (for me) for some reason. Maybe you could provide a working link if it works for you?

@Mr.Xcoder It works for x=1311975312468101214.

@EriktheOutgolfer thanks, my bad

JavaScript (ES6), 40 bytes
Takes input as a string. Throws a recursion error if no index is found.
f=(n,s=k='1')=>n==s?k:f(n,++k&1?k+s:s+k)

Demo

f=(n,s=k='1')=>n==s?k:f(n,++k&1?k+s:s+k)

console.log(f('1')) // 1
console.log(f('12')) // 2
console.log(f('312')) // 3
console.log(f('211917151311975312468101214161820')) // 21
console.log(f('999795939189878583817977757371696765636159575553514947454341393735333129272523211917151311975312468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698100')) // 100

I think you can save a byte with this:  f=(n,s=k='1')=>n-s?f(n,++k&1?k+s:s+k):k

@RickHitchcock Unfortunately, that would force Number comparisons and introduce false positives on large inputs caused by the loss of precision.

Gotcha.  It works on the test cases but was unsure how it would handle other situations.

Jelly, 12 bytes
Rs2ZU1¦ẎVµ€i

Try it online!
Explanation:
Rs2ZU1¦ẎVµ€i
         µ€  Eval this link for each (automatic [1..n] range)
R             Range
 s2           Split in pieces of: 2
   Z          Zip
    U1¦       Only keep index: 1 of: Vectorized reverse
       Ẏ      Flatten 1-deep
        V     Concatenate string versions and eval
           i Find index of y in x (y = implicit input)

05AB1E, 14 bytes
$vDNÌNFs}«})Ik

Try it online!
or as a Test suite
Explanation
0-indexed.
Returns -1 if the input is not in the sequence.
$                 # push 1 and input
 v                # for each y,N (element, index) in input do:
  D               # duplicate top of stack
   NÌ             # push N+2
     NF }         # N times do:
       s          # swap the top 2 elements on the stack
         «        # concatenate the top 2 elements on the stack
          })      # end loop and wrap in a list
            Ik    # get the index of the input in this list

Haha, this is basically my solution with the g removed and the append/prepend thing shortened. I'll delete my answer

@Okx: Oh yeah, I see you golfed yours down to almost exactly this only minutes after my post. Great minds ;)

R, 73 bytes
p=paste0;n=scan(,'');l='';while(l!=n){F=F+1;l="if"(F%%2,p(F,l),p(l,F))};F

Reads from stdin and returns the value of the index (implicitly printed). Infinite loops when the value isn't in the sequence. F is by default FALSE which is cast to 0 when used in arithmetic.
Try it online!

Haskell, 75 71 57 bytes
f n=[i|i<-[1..],(show=<<reverse[1,3..i]++[2,4..i])==n]!!0

Takes n as a string.
Try it online!

Husk, 17 15 bytes
£moiṁsṁṠehGJC2N

Try it online!
1-indexed. Returns 0 if not in the sequence.
-2 bytes from Leo, GJ!

Nice, particularly the z*İ_ trick to reverse alternate elements.  15 bytes by using string input...

String input doesn't really work because values are not lexicographically ordered: Try it online!

There is a shorter way by scanning with J, though: Try it online!

Vyxal, 12 bytes
ɾɖ≬wJṘyRYvṅḟ

Try it Online!
Uses 0-indexing, outputs -1 for invalid.
           ḟ # Find index of input in...
 ɖ           # Scan
ɾ            # range(1, input)
  ≬---       # by
   wJ        # Concatenate
     Ṙ       # Reverse
      yRY    # Reverse every other element
         vṅ  # Concatenate each list into a number

Haskell, 115 85 bytes
s=read.(show=<<)
f 1=1
f x|odd x=s[x,f$x-1]
f x=s[f$x-1,x]
g x=[n|n<-[1..],x==f n]!!0

Try it online!

@BruceForte I actually managed to save 30 thanks to your suggestion.

Mathematica, 135 bytes
s=t={};x=1;While[x<5!,{s~AppendTo~#&,s~PrependTo~#&}[[x~Mod~2+1]]@x;AppendTo[t,FromDigits@Flatten[IntegerDigits/@s]];x++];t~Position~#&

Jelly,  19 18  15 bytes
+ḂḶṚm2;RḤ$ṁµ€Vi

A monadic link taking and returning integers.
Try it online! (very slow - takes ~50s on TIO just to confirm that 3124 is at index 4)
For a much faster version use the previous 18 byter (only checks up to the length of the input, which is sufficient).
How?
+ḂḶṚm2;RḤ$ṁµ€Vi - Link: number, v
           µ€   - perform the monadic link to the left for €ach k in [1,2,3,...v]
                -                 (v can be big, lots of k values makes it slow!)
 Ḃ              -   modulo k by 2  = 1 if odd 0 if even
+               -   add to k = k+isOdd(k)
  Ḷ             -   lowered range = [0,1,2,...,k+isOdd(k)]
   Ṛ            -   reverse = [k+isOdd(k),...,2,1,0])
    m2          -   modulo slice by 2 = [k+isOdd(k),k+isOdd(k)-2,...,3,1]
         $      - last two links as a monad:
       R        -   range(k) = [1,2,3,...,k]
        Ḥ       -   double = [2,4,6,...,2k]
     ;          - concatenate = [k+isOdd(k),k+isOdd(k)-2,...,3,1,2,4,6,...,2k]
         ṁ      - mould like range(k) = [k+isOdd(k),k+isOdd(k)-2,...,3,1,2,4,6,...,k-isOdd(k)]
                -   (this is a list of the integers to be concatenated for index k)
             V  - evaluate as Jelly code (yields a list of the concatenated integers)
              i - first index of v in that (or 0 if not found)

How long would it take to compute 211917151311975312468101214161820?

A long, long time :p

Yes, but how long?

Well looks like it's order v  squared where v is the input integer.

@JonathanAllan Technically you call that ⁸ :p

Swift 4, 92 bytes
This loops infinitely for invalid cases, so I didn't include them in the testing link.
func f(x:String){var i="1",j=1;while i != x{j+=1;i=[i+String(j),String(j)+i][j%2]};print(j)}

Test Suite.
Amusingly, it is longer with a closure:
var f:(String)->Int={var i="1",j=1;while i != $0{j+=1;i=[i+String(j),String(j)+i][j%2]};return j}

Test Suite.

Perl 5, 54 + 1 (-n) = 55 bytes
$a=++$,%2?$,.$a:$a.$,while length$a<length;say/$a/&&$,

Try it online!
Returns nothing if not found.

Japt, 17 bytes
@P=PiXv n X;¥P}a1

Try it online! or check (valid) test cases
Takes input as a string or integer. On invalid input, continues "forever" looking for a solution (thus why I didn't include them in the test cases).
Explanation:
@P=PiXv n X;¥P}a1
                     # Implicitly start with P = ""
@             }a1    # Repeat the function for each integer X > 0 until one returns true
 P=Pi     X          #  Insert X into P at index:
     Xv              #   X is divisible by 2?
        n            #   Times -1
           ;¥P       #  Return whether P now equals the input
                     # Implicitly output the last value of X

The "insert at index" portion might be a bit confusing, so I'll add more detail here. In Japt, NvD is a function which returns 1 if N is divisible by D, and 0 otherwise. If D is not provided, it defaults to 2. Thus Xv  here is equal to 1 if X is even, and 0 if X is odd. NnD is a function that returns D - N. If D is not provided it defaults to 0, effectively returning -N. In this program, that results in -1 if X is even, and still 0 if X is odd. Finally, in Japt indexing negative numbers count from the end of a string or array. Thus the segment PiXv n X evaluates to Pi0 X if X is odd, prepending X, but it evaluates to Pi-1 X if X is even, appending it instead.


text:
Find the nth Aaron number
Background
A Ruth-Aaron pair is a pair of consecutive positive integers n and n+1 such that the sum of the prime factors (counting repeated prime factors) of each integer are equal. For example, (714,715) is a Ruth-Aaron pair, since 714=2*3*7*17, 715=5*11*13, and 2+3+7+17=5+11+13=29. The name Ruth-Aaron pair was chosen by Carl Pomerance in reference to Babe Ruth's career home run total of 714, which stood as the world record from May 25, 1935 until April 8, 1974 when Hank Aaron hit his 715th home run. You can learn more about the fascinating history of these numbers in this Numberphile video.
Goal
Write a complete program or function which, given a positive integer n, outputs the nth Aaron number, where the nth number is defined to be the larger integer of the nth Ruth-Aaron pair. Thus the nth Aaron number is a(n)+1, where a(n) is the nth term in the OEIS sequence A039752.
Test cases
The first few Aaron numbers are
6,9,16,78,126,715,949,1331,1521,1863,2492,3249,4186,4192,5406,5561,5960,6868,8281,8464,10648,12352,14588,16933,17081,18491,20451,24896,26643,26650,28449,28810,33020,37829,37882,41262,42625,43216

Rules

Standard loopholes are forbidden.
Input and output may be in any convenient format.
This is code-golf, the shortest answer (in bytes) wins.

To be sure, "counting multiplicity" means that 20 -> 2, 2, 5 not 2, 5 right?

@Okx I was, I just noticed that when I refreshed his Youtube profile, he had exactly 1 more subscriber (not me)

@HyperNeutrino Yes. I'll edit to make more clear.

Can we choose between 0 and 1 indexing?

@Mr.Xcoder Yes you may

I too, watched today's Numberphile video

I predicted this...

@Okx You mean you predicted this?

Just curious for 1 byte: Can I use 2 indexing?

@Titus I think that's fine

Oh wait ... it´s 3-indexed and saves 3 2 bytes :D nm; that´s penny picking. I´ll go with 1-indexed.

05AB1E, 11 10 9 bytes
-1 byte thanks to Emigna
-1 byte thanks to Adnan
µN>Ð<‚ÒOË

Explanation:
µ            While the counter variable (which starts at 0) is not equal to the input:
 N>          Store the current iteration index + 1, and then create an array with
   Ð<‚       [current iteration index + 1, current iteration index]
      ÒO     Get the sum of the prime factors of each element
        Ë    If all elements in the array are equal,
             implicitly increment the counter variable

1-indexed.
Try it online!

Explanation when you can, please :)

@Mr.Xcoder Added.

10 bytes: µN>Ð<‚ÒOË½

@Emigna Ah, nice one.

You can leave out the ½ as this will be auto-appended when missing in the µ-loop body

@Adhnan Really? That's a crazy language feature.

Husk, 11 9 bytes
-2 bytes thanks to a clever golf by @Leo
€∫Ẋ¤=oΣpN

Try it online!
Explanation
  Ẋ     N   -- map function over all consecutive pairs ... of natural numbers           [(1,2),(2,3),(3,4),(4,5)...]
   ¤=       --   are the results of the following function equal for both in the pair?
     oΣp    --     sum of prime factors                                                   [0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0]
 ∫          -- cumulative sum                                                           [0,0,0,0,0,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3]
€           -- the index of the first value equal to the input

Nice work, I was about to post substantially the same idea :)

A golfier version https://tio.run/##ARsA5P9odXNr///igqziiKvhuorCpD1vzqNwTv///zY

@Leo Ooh, €∫ is a really nice trick! And one that only works in a lazy language. ;)

@Leo Very clever.

Jelly, 12 bytes
;‘ÆfS€Eµ⁸#Ṫ‘

A monadic link taking and returning non-negative numbers
Try it online!
How?
;‘ÆfS€Eµ⁸#Ṫ‘ - Link: number, n
         #   - n-find (counting up, say with i, from implicit 1)
        ⁸    - ...number of matches to find: chain's left argument, n
       µ     - ...action: the monadic chain with argument i:
 ‘           -   increment = i+1
;            -   concatenate = [i,i+1]
  Æf         -   prime factors (with duplicates, vectorises)
    S€       -   sum €ach
      E      -   all (two of them) equal?
          Ṫ  - tail, the last matching (hence nth) i
           ‘ - increment (need to return i+1)

Save a byte with ;’ÆfS€E_Ịµ#.

Still need the tail.

And that's what you get for testing only with 1.

MATL, 17 bytes
`@:"@Yfs]vd~sG<}@

1-based. Very slow.
Try it online!
Explanation
`        % Do...while
  @      %   Push iteration index k, starting at 1
  :      %   Range [1 2 ... k]
  "      %   For each j in [1 2 ... k]
    @    %     Push j
    Yf   %     Row vector of prime factors
    s    %     Sum
  ]      %   End
  v      %   Concatenate whole stack into a column vector
  d      %   Consecutive differences. A zero indicates a Ruth-Aaron pair
  ~s     %   Number of zeros
  G<     %   Is it less than the input? If so: next k. Else: exit loop
}        % Finally (execute right before when the loop is exited)
  @      %   Push current k
         % Implicit end. Implicit display

Pyth, 23 20 bytes
This is 1-indexed.
WhQ=-QqsPZsPhZ=+Z1;Z

Test Suite or Try it online!

Explanation

WhQ=-QqsPZsPhZ=+Z1;Z  - Full program. Takes input from Standard input.

WhQ                      - While Q is still higher than 0.
       sPZ               - Sum of the prime factors of Z.
          sPhZ           - Sum of the prime factors of Z+1.
      q                  - If the above are equal:
   =-Q                     - Decrement Q by 1 if they are equal, and by 0 if they are not.
              =+Z1;      - Increment Z on each iteration.
                   Z     - Output Z.

PHP, 93 92 91+1 bytes
while(2+$argn-=$a==$b)for($b=$a,$a=!$x=$n+=$k=1;$k++<$x;)for(;$x%$k<1;$x/=$k)$a+=$k;echo$n;

Run as pipe with -nR or try it online.
-2 bytes with 3-indexed (fist Aaron number for argument 3): remove 2+.
breakdown
while(2+$argn       # loop until argument reaches -2 (0 and 1 are false positives)
    -=$a==$b)           # 0. if factors sum equals previous, decrement argument
    for($b=$a,          # 1. remember factors sum
        $a=!            # 3. reset factors sum $a
        $x=$n+=         # 2. pre-increment $n and copy to $x
        $k=1;$k++<$x;)  # 4. loop $k from 2 to $x
        for(;$x%$k<1;       # while $k divides $x
            $x/=$k)             # 2. and divide $x by $k
            $a+=$k;             # 1. add $k to factors sum
echo$n;             # print Aaron number $n

Mathematica, 97 bytes
(t=r=1;While[t<=#,If[SameQ@@(Plus@@((#&@@# #[[2]])&/@FactorInteger@#)&/@{#,#+1}&@r),t++];r++];r)&

Try it online!

It needs to output the larger of the pair according to the description; 6 returns 714 instead of 715, for example.

@numbermaniac fixed! saved 2 bytes!

Pyth, 12 11 bytes
e.fqsPtZsPZ

Indexing from 1 removes a byte, and puts Pyth ahead of Jelly

Explanation

e.fqsPtZsPZ  - Full program. Takes input from Standard input.

e.f          - Last element of the list of the first $input numbers for which
   q         - Are equal
    s   s    - The sum of
     PtZ PZ  - Prime factors of $number-1 and $number

Jelly, 17 bytes
ÆfS=’ÆfS$$µ³‘¤#ṖṪ

Try it online!
Explanation
ÆfS=’ÆfS$$µ³‘¤#ṖṪ  Main link, argument is z
              #    Find the first       elements that satisfy condition y: <y><z>#
           ³‘¤                    z + 1
          µ        Monadic link, where the condition is:
  S                The sum of
Æf                            the array of primes that multiply to the number
   =               equals
       S           The sum of
     Æf                       the prime factors of
    ’                                              the number before it
        $$         Last two links as a monad, twice
               Ṗ   k -> k[:-1]
                Ṫ  Last element (combined with `pop`, gets the second last element)

1-indexed

I am not sure 2-indexing is allowed by default rules.

@Mr.Xcoder Sure, fixed.

Ruby, 89 86 bytes
->n{(1..1/s=0.0).find{|x|r,c=2,0
0while x%r<1?(x/=r;c+=r):x>=r+=1
(c==s)?0>n-=1:!s=c}}

Try it online!

Japt, 19 bytes
1+_°k x ¥Zk x «U´}a

Uses 1-indexing.
Try it online!

Python 2, 119 104 102 101 bytes
f=lambda n,k=2:n/k and(f(n,k+1),k+f(n/k))[n%k<1]
i=input();g=0
while-~i:i-=f(g)==f(g+1);g+=1
print(g)

Try it online!
-17 bytes thanks to @ovs!
-1 byte thanks to @notjagan
Credit goes to Dennis for the prime factorization algorithm. 1-indexed.

Note: This is extremely slow and inefficient. Inputs higher than 7 will crash unless you set import sys and do sys.setrecursionlimit(100000), but it works in theory.

104 bytes by making f a function calculating the sum of prime factors

Would be great if you would track your bytecount (and maybe comment your edits).

(f(n,k+1),k+f(n/k))[n%k<1] for another -2 bytes. This makes it even slower.

-1 byte by switching i+1 to -~i.

Japt, 14 bytes
Èk x ¶Yk x}iU1

Try it

Gaia, 13 bytes
⟨:)ḍΣ¤ḍΣ=⟩#e)

Try it online!


text:
Is it a semiprime?
Surprisingly, I don't think we have a code-golf question for determining if a number is semiprime.

A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers.

Simple enough, but a remarkably important concept.
Given a positive integer, determine if it is a semiprime. Your output can be in any form so long as it gives the same output for any truthy or falsey value. You may also assume your input is reasonably small enough that performance or overflow aren't an issue.
Test cases:
input -> output
1     -> false
2     -> false
3     -> false
4     -> true
6     -> true
8     -> false
30    -> false   (5 * 3 * 2), note it must be EXACTLY 2 (non-distinct) primes
49    -> true    (7 * 7)      still technically 2 primes
95    -> true
25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784406918290641249515082189298559149176184502808489120072844992687392807287776735971418347270261896375014971824691165077613379859095700097330459748808428401797429100642458691817195118746121515172654632282216869987549182422433637259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133844143603833904414952634432190114657544454178424020924616515723350778707749817125772467962926386356373289912154831438167899885040445364023527381951378636564391212010397122822120720357
      -> true, and go call someone, you just cracked RSA-2048

This is code-golf, so standard rules apply!

@WheatWizard There's a slightly difference in that that one asks for 3 primes (not a big difference for almost all languages) and it's for distinct primes only (fairly different for some languages). I can discuss it with you in chat if you'd like to continue a more detailed discussion.

@HyperNeutrino I think the difference is negligible. How many product of n primes questions are we going to allow?  In my opinion we already have enough and this new one adds nothing interesting to the mix.

@WheatWizard You raise a good point, but similarly, we already have a bunch of many types of questions, and although, in contrast to what you express, most of them do add significant contribution to their area, this question has enough of a difference that I would believe that it warrants a separate question/post.

@hyperneutrino looking at the answers on both challenges, it looks like the difference is a single number in the source code, 2 vs 3. I would hardly call that a big difference.

@WheatWizard There is also "distinct" vs "not distinct"...

@WheatWizard For example, if you compare the Jelly answer on that one: ÆEḟ0⁼7B¤ to the Jelly answer on this one: ÆfL=2, you'll notice that there is a significant difference; namely, that one has to check for distinctness.

You're my hero, @HyperNeutrino. In the future I'll look for further distinct questions.

@HyperNeutrino We disagree, I don't think this is worth arguing any further.

@LordFarquaad Just because its a duplicate doesn't mean it is bad.  In my mind being a duplicate is a good thing, it means that you are asking a thing that the community finds interesting enough to have already asked about.

@WheatWizard Agreed. (well, disagreed). I'd rather not argue further. It's borderline dupe but it's been antihammered so I won't bother arguing for either side for this question's sake :P

OEIS A001358

Subset of this and (partially) this

If you can work out that some very large number is a semiprime that doesn't mean you've cracked RSA-2048, does it? Don't you need to know the two prime factors as well as that it's semiprime to crack it?

@CJDennis You're right, but is there a test for semi-primeness beyond calculating the factors and counting them? From what I've seen (which admittedly is not a lot), finding the factors is necessary to test semi-primeness, you just don't hold onto them.

Brachylog, 2 bytes
Basically a port from Fatalize's answer to the Sphenic number challenge.
ḋĊ

Try it online!
How?
ḋĊ - implicitly takes input
ḋ  - prime factorisation (with duplicates included)
 Ċ - is a couple

Right language for the job indeed :P

@Uriel Ċ is actually a built-in list of two variables; being a declarative language the output is, by default, a test for satisfaction (e.g. ḋ on its own would output true. for non-negative integers).

How is this 2 bytes?

@harold I just updated to make "bytes" in the header link to Brachylog's code-page. A hex dump would be c6 eb.

Husk, 4 bytes
Look ma no Unicode!
=2Lp

Try it online!
How?
=2Lp - a one input function
   p - prime factorisation (with duplicates included)
  L  - length
=2   - equals 2?

Pyth, 4 bytes
q2lP

Test suite.

How?
q2lPQ     - Q is implicit input.

q2        - Is equal to 2?
    lPQ   - The length of the prime factors of the input.

Darn it, shorter builtins! :(

Python 3, 54 bytes
lambda n:0<sum((n%x<1)+(x**3==n)for x in range(2,n))<3

Try it online!
The previous verson had some rounding issues on large cube numbers (125,343,etc)
This calculates the amount of divisors (not only primes), if it has 1 or 2 it returns True.
The only exception is when a number has more than two prime factors but only two divisors. In this case it is a perfect cube of a prime (its divisors are its cube root and its cube root squared). x**3==n will cover this case, adding one to the cube root entry pushes the sum up to a count of 3 and stops the false-positive.
thanks Jonathan Allan for writing with this beautiful explanation

This claims 8 is semiprime

n**(1/3)%1>0<sum... should work.

@xnor fixed it.

Made a tiny edit (e.g. 6 cubed has many more divisors)

Mathematica, 16 bytes
PrimeOmega@#==2&

PrimeOmega counts the number of prime factors, counting multiplicity.

Dang, there's a builtin?

@JungHwanMin If only there was SemiprimeQ

Nice. I didn't know about PrimeOmega

Ruby, 56 48 bytes
->x{r=c=2;0while x%r<1?(x/=r;c-=1):x>=r+=1;c==0}

Try it online!
How it works:
->x{                    # Lambda function
    r=c=2;              # Starting from r=2, c=2
    0 while             # Repeat (0 counts as a nop)
        x%r<1? (        # If x mod r == 0
            x/=r:       # Divide x by r
            c-=1        # decrease c
        ):              # else
            x>=r+=1     # increase r, terminate if r>x
    );
    c==0                # True if we found 2 factors
}

Thanks Value Ink for the idea that saved 8 bytes.

Why not just have c start at 0 and count up, instead of making it an array that you add all the factors to? That way you take out the need to use size at the end

You are right, it's because I wrote the factorization function for another challenge and I reused it here.

Mathematica, 31 29 bytes
Tr[Last/@FactorInteger@#]==2&

Python 2, 67 bytes
lambda k:f(k)==2
f=lambda n,k=2:n/k and(f(n,k+1),1+f(n/k,k))[n%k<1]

Try it online!
-10 bytes thanks to @JonathanAllan!
Credit for the Prime factorization algorithm goes to Dennis (in the initial version)

Did you use the code from Dennis' answer? If so, you should give credit.

@totallyhuman Oh yeah, sorry. I used it in 2 different answers today and I gave him credit in one of them, but I have forgotten to do that here once more. Thanks for spotting that!

67 bytes

@JonathanAllan Wow, thanks a lot!

55 bytes

@HalvardHummel It is too similar to other answers. I will not update

Didn't realise there where other Python answers. My bad

Neim, 4 bytes
δ

Try it online!

Can you explain how this is 4 bytes?... I am totally confused.

Lol I just had this

@Mr.Xcoder Neim has a custom code-page

@Mr.Xcoder Using the Neim codepage, this is , , δ, and `` as single-bytes.

@HyperNeutrino I just obfuscated the 2 a little bit, and now this is the only answer without 2 :)

heh

@HyperNeutrino ono whatever should i do adds builtin for checking for semiprimaity

Mathematica 32 bytes
Thanks to ngenesis for 1 byte saved
Tr@FactorInteger[#][[;;,2]]==2&

Save one byte by using ;; instead of All.

JavaScript (ES6), 47 bytes
Returns a boolean.
n=>(k=1)==(d=n=>++k<n?n%k?d(n):d(n/k--)+1:0)(n)

Demo

let f =

n=>(k=1)==(d=n=>++k<n?n%k?d(n):d(n/k--)+1:0)(n)

console.log(
  [...Array(200).keys()].filter(f).join`, `
)

Regex (ECMAScript or better), 24 23 bytes
(?=((x(x*))\2+)\1+$)\3^

-1 byte thanks to Grimmy
Try it online! - ECMAScript
Try it online! - Python
Try it online! - Ruby
Takes its input in unary, as a string of x characters whose length represents the number.
This regex is based on the 18 byte "Is it prime?" regex (?=(x(x*))\1+$)\2^, which unlike its semiprime version above, is longer than the shortest known, the 16 byte ^(?!(xx+)\1+$)xx. But like ^(?=(xx+?)\1*$)\1$ (also 18 bytes), it has the interesting attribute of implicitly rejecting 0 and 1 as prime numbers, whereas the 16 byte regex must explicitly reject them (the xx at the end).
                  # tail = N = input number; there's no need to anchor here,
                  # because a start anchor is used at the end of this regex
(?=
    (             # \1 = largest proper divisor of N that is >=2
        (x(x*))   # \2 = largest proper divisor of \1; \3 = \2 - 1
        \2+       # Assert that \2 is a proper divisor of \1
    )
    \1+$          # Assert that \1 is a proper divisor of N
)
\3^               # Assert that \3==0, and thus \2==1, meaning the largest proper
                  # divisor of the largest proper divisor of N is 1, meaning N is
                  # semiprime

Regex (Perl / Java / PCRE / Pythonregex / .NET), 23 bytes
^(?>((x(x*))\2+)\1+$)\3

Try it online! - Perl
Try it online! - Java
Try it online! - PCRE
Try it online! - Python import regex
Try it online! - .NET
This is a direct port of the "ECMAScript or better" regex above, using an atomic group instead of an atomic lookahead. It is much faster on most regex engines, as the ^ start-anchor test is done first instead of last.
Regex (Perl / Java / PCRE / Pythonregex), 23 bytes
^((x+)\2*(?=\2$)){2}+x$

Try it online! - Perl
Try it online! - Java
Try it online! - PCRE
Try it online! - Python import regex
This is a port of the now-obsoleted 24 byte "ECMAScript or better" regex, using a possessive quantifier instead of an atomic lookahead to disable backtracking.
^                   # tail = input number
(
    (x+)            # \2 = largest strict divisor of tail
                    #    = tail / {smallest prime factor of tail}
    \2*(?=\2$)      # Assert that \2 is a strict divisor of tail; tail = \2
){2}+               # Execute the loop exactly 2 times, with backtracking disabled
x$                  # assert tail == 1

\$\large\textit{Expressions with interactive input}\$
R, 59 58 54 bytes
grepl('^((.+)\\2*(?=\\2$)){2}+.$',strrep(1,scan()),,1)

Try it online! - test cases only
\$\large\textit{Anonymous functions}\$
R, 63 62 58 53 bytes
\(n)grepl('^((.+)\\2*(?=\\2$)){2}+.$',strrep(1,n),,1)

Attempt This Online!
-1 byte thanks to Giuseppe
-4 bytes by using grepl() instead of sum(grep()) or any(grep())
-5 bytes by using a new anonymous function syntax introduced in R v4.1.0
The old 58 byte R v3.5.2 function: Try it online!
Ruby, 37 36 bytes
->n{?x*n=~/(?=((x(x*))\2+)\1+$)\3^/}

Try it online!
Try it online! - test cases only
PHP, 62 bytes
fn($n)=>preg_match('/^((.+)\2*(?=\2$)){2}+.$/',str_pad('',$n))

Try it online!
JavaScript (ES6), 46 45 bytes
n=>/(?=((.(.*))\2+)\1+$)\3^/.test(Array(n+1))

Try it online!
Java 8, 61 bytes
n->new String(new char[n]).matches("((.+)\\2*(?=\\2$)){2}+.")

Try it online!
Try it online! - test cases only
Java 11, 51 bytes
n->"x".repeat(n).matches("((x+)\\2*(?=\\2$)){2}+x")

Try it online!
\$\large\textit{Full programs}\$
Retina, 30 29 bytes
.+
$*
^(?>((1(1*))\2+)\1+$)\3

Try it online! - test cases only
PHP, 64 bytes
<?=preg_match('/^((.+)\2*(?=\2$)){2}+.$/',str_pad('',$argv[1]));

Try it online! - tests one number at a time
PHP -F, 61 bytes
<?=preg_match('/^((.+)\2*(?=\2$)){2}+.$/',str_pad('',$argn));

Try it online! - tests ranges of numbers
Try it online! - tests one number at a time

I'll forgive you for missing this conversation. 23 bytes

@H.PWiz Oh! Thanks. I came up with (?=(x(x*))\1+$)\2^ independently on 2021-03-06 (basing it on my earlier finding of ^(?>(x(x*))\1+$)\2 on 2018-12-07), and didn't realize Grimmy had already come up with it on 2019-04-21. Cool that a method that's longer for primes can be shorter for semiprimes.

J-uby + prime, 34 bytes
:prime_division|:*&:pop|:sum|:==&2

Try it online!

Jelly, 5 bytes
ÆfL=2

Try it online!
Explanation
ÆfL=2  Main link
Æf     Prime factors
  L    Length
   =   Equals
    2  2

Actually, 4 bytes
ol2=

Try it online!

05AB1E, 4 bytes
Òg2Q

Try it online!
How?
Ò       prime factors list (with duplicates)
 g      length
   Q    equal to
  2     2

Dyalog APL, 18 bytes
⎕CY'dfns'
2=≢3pco⎕

Try it online!
How?
⎕CY'dfns' - import pco
3pco⎕ - run pco on input with left argument 3 (prime factors)
2=≢ - length = 2?

MATL, 5 bytes
Yfn2=

Try it online!
Explanation

Yf - Prime factors.

n - Length.

2= - Is equal to 2?

Python with SymPy 1.1.1,  57  44 bytes
-13 bytes thanks to alephalpha (use 1.1.1's primeomega)
from sympy import*
lambda n:primeomega(n)==2

Try it online!

lambda n:primeomega(n)==2

Ah that reminds me to upgrade from 1.0, thanks!

Gaia, 4 bytes
ḍl2=

4 bytes seems to be a common length, I wonder why... :P
Try it online!
Explanation
ḍ     Prime factors
 l    Length
  2=  Equals 2?

4 bytes seems to be a common length, I wonder why... - Probably because all answers are prime factors, length, is equal to 2?

@MrXcoder Yep, exactly

4 of which are mine BTW >_>

4 is also the first semiprime. Spooky!

R, 67 bytes
c=0;n=scan();for(p in(1:n)[-1:-2]-1)while(n%%p<1){c=c+1;n=n/p};c==2

Try it online!

Java 8, 69 61 bytes
n->{int r=1,c=2;for(;r++<n;)for(;n%r<1;n/=r)c--;return c==0;}

-8 bytes thanks to @Nevay.
Try it here.

You can remove the else statement (which could be else++r;) to save 8 bytes n->{int r=1,c=2;for(;r++<n;)for(;n%r<1;n/=r)c--;return c==0;}.

This ties with my regex solution at 61 bytes.

@Deadcode Actually, yours can be 10 bytes shorter by changing new String(new char[n]) to "x".repeat(n) (Java 11+). :)

Ah, nice! It even works in TIO. Hmm... I know I saw this method before, as I had already upvoted this. Can't think of any reason I wouldn't have just included both, unless it didn't work on TIO back then... but TIO already stopped being updated by then, so I don't know.

Ruby, 35+8 = 43 bytes
Uses the -rprime flag to unlock the prime_division function.
->n{n.prime_division.sum(&:pop)==2}

Try it online!

Vyxal, 3 bytes
ǐḢ₃

Try it Online!

Factor + math.primes.factors, 22 bytes
[ factors length 2 = ]

Try it online!

Python 2, 75 65 bytes
lambda n:g(n)==2
g=lambda n,i=2:n/i and[g(n,i+1),1+g(n/i)][n%i<1]

Try it online!
All credit to xnor's answer for the original prime factorization code.

Japt, 6 5 bytes
k Ê¥2

Test it online

Explanation
Does pretty much the same as most of the other answers: k gets the array of prime factors, Ê gets its length and ¥ checks for equality with 2.

÷k o)j also works, unfortunately it's the same length :-(

C#, 112 Bytes
n=>{var r=Enumerable.Range(2,n);var l=r.Where(i=>r.All(x=>r.All(y=>y*x!=i)));return l.Any(x=>l.Any(y=>y*x==n));}

With formatting applied:
n =>
{
    var r = Enumerable.Range (2, n);
    var l = r.Where (i => r.All (x => r.All (y => y * x != i)));
    return l.Any (x => l.Any (y => y * x == n));
}

And as test program:
using System;
using System.Linq;

namespace S
{
    class P
    {
        static void Main ()
        {
            var f = new Func<int, bool> (
                n =>
                {
                    var r = Enumerable.Range (2, n);
                    var l = r.Where (i => r.All (x => r.All (y => y * x != i)));
                    return l.Any (x => l.Any (y => y * x == n));
                }
            );

            for (var i = 0; i < 100; i++)
                Console.WriteLine ($"{i} -> {f (i)}");
            Console.ReadLine ();
        }
    }
}

Which has the output:
0 -> False
1 -> False
2 -> False
3 -> False
4 -> True
5 -> False
6 -> True
7 -> False
8 -> False
9 -> True
10 -> True
11 -> False
12 -> False
13 -> False
14 -> True
15 -> True
16 -> False
17 -> False
18 -> False
19 -> False
20 -> False
21 -> True
22 -> True
23 -> False
24 -> False
25 -> True
26 -> True
27 -> False
28 -> False
29 -> False
30 -> False
31 -> False
32 -> False
33 -> True
34 -> True
35 -> True
36 -> False
37 -> False
38 -> True
39 -> True
40 -> False
41 -> False
42 -> False
43 -> False
44 -> False
45 -> False
46 -> True
47 -> False
48 -> False
49 -> True
50 -> False
51 -> True
52 -> False
53 -> False
54 -> False
55 -> True
56 -> False
57 -> True
58 -> True
59 -> False
60 -> False
61 -> False
62 -> True
63 -> False
64 -> False
65 -> True
66 -> False
67 -> False
68 -> False
69 -> True
70 -> False
71 -> False
72 -> False
73 -> False
74 -> True
75 -> False
76 -> False
77 -> True
78 -> False
79 -> False
80 -> False
81 -> False
82 -> True
83 -> False
84 -> False
85 -> True
86 -> True
87 -> True
88 -> False
89 -> False
90 -> False
91 -> True
92 -> False
93 -> True
94 -> True
95 -> True
96 -> False
97 -> False
98 -> False
99 -> False

Pari/GP, 17 bytes
n->bigomega(n)==2

Try it online!

Python 2, 90 bytes
def g(x,i=2):
 while x%i:i+=1
 return i
def f(n,l=0):
 while 1%n:l+=1;n/=g(n)
 return l==2

f takes an integer n greater than or equal to 1, returns boolean.
Try it online!
Test cases:
>>> f(1)
False
>>> f(2)
False
>>> f(3)
False
>>> f(4)
True
>>> f(6)
True
>>> f(8)
False
>>> f(30)
False
>>> f(49)
True
>>> f(95)
True

Retina, 45 bytes
.+
$*
^(11+)(\1)+$
$1;1$#2$*
A`\b(11+)\1+\b
;

Try it online! Link includes test cases. Explanation:
.+
$*

Convert to unary.
^(11+)(\1)+$
$1;1$#2$*

Try to find two factors.
A`\b(11+)\1+\b

Ensure both factors are prime.
;

Ensure two factors were found.

J, 6 bytes
5 bytes will work as a one-off:
   2=#q: 8
0
   2=#q: 9
1

I believe I need six when I define the function:
   semiprime =. 2=#@q:
   (,. semiprime) 1 + i. 20
 1 0
 2 0
 3 0
 4 1
 5 0
 6 1
 7 0
 8 0
 9 1
10 1
11 0
12 0
13 0
14 1
15 1
16 0
17 0
18 0
19 0
20 0

Pyke, 5 bytes
Pl02q

Try it here!

Thunno 2, 4 bytes
fl2=

Attempt This Online! Link is to verbose version of code.
f      # prime factors
 l     # length
  2=   # equal to 2?

Braingolf, 8 bytes
pl2e1:0|

Try it online!

Perl 6, 43 bytes
{my \f=first $_%%*,2..$_;?f&&is-prime $_/f}

Try it online!
f is the smallest factor greater than 1 of the input argument $_, or Nil if $_ is 1.  The return value of the function is true if f is true (ie, not Nil) AND the input argument divided by the factor is prime.
If $_ itself is prime, then f will be equal to $_, and $_ / f is 1, which is not prime, so the formula works in that case as well.

PHP, 75 bytes
<?php for($c=$t=2;$n=&$argv[1]>1;$t++)while($n%$t<1){$c--;$n/=$t;}echo+!$c;

Try it online!
This script is called from the command line with the number being tested as its parameter. It prints out a 1 if the number was a semi-prime, else a 0.
Explanation
<?php

Work through each integer, $t, from 2 up, to see if it's a factor. We need to keep
going, dividing by the factors until $n (an alias for
$argv[1], the first CLI parameter) reaches 1. (And as there is a 2 to hand, we take the
chance to initialize the counter, $c, to 2.)
for ($c = $t = 2; $n = &$argv[1] > 1; $t++)

When we find a factor, we keep using it for as long as we can…
    while ($n % $t < 1) {

…each time deccrementing the factor counter…
        $c--;

…and recalculating our number.
        $n /= $t;
    }

When we reach the end, the counter can only be 0 if there were 2 factors. We ‘not’
the number, but this converts it to a boolean, so we use + to make it into 1
(the number was a semi-prime) or 0 (it wasn’t).
echo +!$c;

APL(NARS), 7 chars, 14 bytes
{2=≢π⍵}

test:
  f←{2=≢π⍵}
  f¨1 2 3 4 6 8 30 49 95
0 0 0 1 1 0 0 1 1

Alice, 15 bytes
/O\cdtv
@I/ nt<

Try it online!
Flattened
IcdttnO   Full program
I         Read the input
 c        Get the prime factors in the stack
  dtt     Depth of the stack - 2
     n    Negate, becomes 1 if there was only 2 prime factors, 0 otherwise
      O   Print the result

cQuents, 5 bytes
2=Lq$

Try it online!
1 for truthy, 0 for falsey.
Explanation
       each term in the sequence is
2                                   2
 =                                    ==
  L                                      length (
   q                                              prime factors (
    $                                                             current index


text:
Implement a whitespace golfer
Some two-dimensional esolangs, such as Forked, and some non-esolangs, such as Python, can sometimes require spaces before lines of code. This isn't very golfy. Also, I'm lazy and writing a 2d lang that needs lots of spaces before code. Your task is to write a tool that makes these languages golfier.
Of course, this will not be perfect; it cannot be used, for instance, when a number is the first character on a line of source. However, it will generally be useful.
Challenge
You will write a program or function that either...

...takes one argument, a filename or a string, or...
...reads from standard input.

Your program will act like cat, except:

If the first character on any line is a number, your code will print x spaces, where x is that number.
Otherwise, it will simply be printed.
As will every other character in the input.

Test cases
Input:
foo bar foo bar
1foo bar foo bar foo bar
2foo bar foo bar foo bar foo bar

Output:
foo bar foo bar
 foo bar foo bar foo bar
  foo bar foo bar foo bar foo bar

Input:
--------v
8|
8|
80
8,
7&

Output:
--------v
        |
        |
        0
        ,
       &

Input:
foo bar
bar foo
foo bar

Output:
foo bar
bar foo
foo bar

Input:
0123456789
1234567890
2345678901
3456789012
4567890123

Output:
123456789
 234567890
  345678901
   456789012
    567890123

Rules

Output must be exactly as input, except for lines where the first character is a number.
Your program cannot append/prepend anything to the file, except one trailing newline if you desire.
Your program may make no assumptions about the input. It may contain empty lines, no numbers, Unicode characters, whatever.
If a number with more than one digit starts a line (e.g. 523abcdefg), only the first digit (in the example, 5) should turn into spaces.

Winner
Shortest code in each language wins. Have fun and good luck!

Sandboxed post

Of course, this will not be perfect; it cannot be used, for instance, when a number is the first character on a line of source. Not true, just make the first character a 0 (ahem, your last test case)

Can we read a list of strings from stdin (is this valid)?

Retina, 9 bytes
m`^\d
$*

Try it online! Note: Trailing space on last line.

Cubically, 69 66 bytes
RBR3B~(+50<7?6{+54>7?6{-002+7~?6{(@5*1-1/1)6}}}(-6>7?6&@7+70-4~)6)

Try it online!
Explanation:
First we do this initialization:
RBR3B

To set up this cube:
   533
   004
   000
411223455441
311222331440
311222331440
   555
   555
   200

The most important thing about this cube is that face 5 sums to 32, which is the value required to print spaces. Coincidentally, it also happens to be fairly short for all other computation. After that is done:
~( . . . )                                    Takes the first input, then loops indefinitely

  +50<7?6{+54>7?6{-002+7~?6{(@5*1-1/1)6}}}    Handle leading digit:
  +50<7?6{                               }    If input is greater than 47 ('0' is 48)
          +54>7?6{                      }     And input is less than 58 ('9' is 57)
                                              Then input is a digit
                  -002+7                      Set notepad equal to value of input digit
                        ~                     Take next input (only convenient place for it)
                         ?6{           }      If the notepad isn't 0
                            (        )6       While the notepad isn't 0:
                             @5                 Print a space
                               *1-1/1           Decrement the notepad by one
                                              Leading digit handled

     (-6>7?6&@7+70-4~)6                       Handle rest of line:
     (               )6                       While the notepad isn't 0:
      -6>7?6&                                   Exit if End of Input
             @7                                 Print the next character
               +70-4                            Set notepad to 0 if it was a newline
                    ~                           Take the next character

Wow, that's a good use of nested ... everything. +1

Husk, 15 13 bytes
-2 bytes thanks to @Zgarb
mΓo+?oR' i;±¶

Try it online!
Uses the same technique as @Jonathan Allan
Explanation
             ¶  -- split input into a list of lines
m               -- apply the following function to each line
 Γ              --   deconstruct the string into a head and a tail
  o+            --   prepend to the tail of the string ...
    ?      ±    --     if the head is a digit (n)
     oR' i      --       the string of n spaces
                --     else
          ;     --       the head of the string
                -- implicitly print list of strings line-by-line

13 bytes with the use of Γ.

JavaScript (ES8), 38 37 bytes
a=>a.replace(/^\d/gm,a=>''.padEnd(a))

I don't think it can be improved much more.
Saved 1 byte thanks to Shaggy - Use ES8 features.

"I don't think it can be improved much more." - You could save a byte by using ES8's padEnd like so: s=>s.replace(/^\d/gm,m=>"".padEnd(m))

@Shaggy. I didn't know ES8 is allowed already. Thanks.

If there's any single interpreter (i.e.,browser) out there that supports a feature then that feature is fair game here :)

Ruby, 24 21+1 = 25 22 bytes
Uses the -p flag. -3 bytes from GB.
sub(/^\d/){"%#$&s"%p}

Try it online!

{"%#$&s"%""} saves 1 byte

And another byte if you use sub instead of gsub

@GB and another byte by putting %p at the end instead of %"". Thanks for your help!

Python 2, 98 74 67 65 bytes
-24 bytes thanks to Jonathan Allan. -7 bytes thanks to Mr. Xcoder.
for i in open('f'):print' '*int(i[0])+i[1:]if'/'<i[:1]<':'else i,

Try it online!
Takes input in the file named f.

Also errors when no digit in the first character of a line (when using a list as a way to choose items all the elements are evaluated)

back to 89

87 bytes - TIO link's header is mocking open; code is expecting a file named 'f'. I think it's OK?

Ah, true the ' '*0 is falsey. Using [:1] is still a save though. No need for read I believe (and it would be readlines) since the default behaviour of open is to iterate through the lines. Also there is no need for the mode since 'r' is the default. If I'm right that's 73 !

Let us continue this discussion in chat.

71 bytes. isdigit() can be replaced by lexicographical comparison, which saves tons of bytes

67 bytes: for i in open('f'):print(' '*int(i[0])+i[1:]if"/"<i[:1]<":"else i),. It is better to add the whole string at once, saves 4 bytes.

05AB1E, 10 bytes
v0y¬dićú},

Try it online!

How does one input with empty lines?

No idea lol... I'll look into it

|vy¬dićú}, works for 10 bytes.

OK, it's not one cannot input an empty line, it's that the code does not work for an empty line: if one uses a single zero it works, so it must be something about the head not existing (same goes for @Riley's suggested 10 byter by the way).

@JonathanAllan It has something to do with the way | works. It is supposed to push the rest of input as an array with strings, but it stops at empty lines (TIO). I brought this up in the 05AB1E chatroom if you want to know more.

I've confirmed that | does not allow empty lines, since that is the signal to end fetching see this line of code.

Furthermore EvyćDdið×}?, or Evy¬dićú}, still dont work because the empty string has no head, so would need replacing with zero prior to the rest of the processing.

Using @Riley's 10 byter and modifying to accept a single input as a list of strings works for 12 bytes as Ev0yë¬dićú}, though.

@JonathanAllan v0y¬dićú}, should work. And we're back to 10 bytes :)

Python 3, 95 bytes
lambda y:'\n'.join(re.sub('^\d',lambda x:' '*int(x.group()),z)for z in y.split('\n'))
import re

Try it online!
-4 bytes by stealing the regex idea from ThePirateBay

You stole from ThePirateBay, how the tables have turned

@Moonstroke HAH lol I didn't even notice that :P

Jelly, 19 bytes
V⁶ẋ
ḢÇ¹e?ØD;
ỴÇ€Yḟ0

A monadic link taking and returning lists of characters, or a full program printing the result.
Try it online!
How?
V⁶ẋ - Link 1, make spaces: character (a digit)
V   - evaluate as Jelly code (get the number the character represents)
 ⁶  - a space character
  ẋ - repeat

ḢÇ¹e?ØD; - Link 2, process a line: list of characters
Ḣ        - head (get the first character and modify the line)
         -   Note: yields zero for empty lines
     ØD  - digit characters = "0123456789"
    ?    - if:
   e     - ...condition: exists in? (is the head a digit?)
 Ç       - ...then: call the last link as a monad (with the head as an argument)
  ¹      - ...else: identity (do nothing; yields the head)
       ; - concatenate with the beheaded line

ỴÇ€Yḟ0 - Main link: list of characters
Ỵ      - split at newlines
 Ç€    - call the last link (1) as a monad for €ach
   Y   - join with newlines
    ḟ0 - filter out any zeros (the results of empty lines)

beheaded line Is that the actual term? xD

Well, it is now :)

Ahahaha I tried outgolfing you and ended up with a solution essentially identical to yours xD

Perl 5, 13 + 1 (-p) = 14 bytes
s/^\d/$"x$&/e

Try it online!

Python 2, 76 72 68 bytes
-4 bytes thanks to @ovs!
@DeadPossum suggested switching to Python 2, which saved 4 bytes too.
Just thought it's nice to have a competitive full program in Python 2 that does not explicitly check if the first character is a digit. This reads the input from a file, f.
for i in open('f'):
 try:r=int(i[0])*" "+i[1:]
 except:r=i
 print r,

Try it online! (courtesy of @ovs)

@ovs Thanks for that

@ovs What did you change (I will do it by hand) ? It tells me that the permalink cannot be decoded

Instead of printing in every iteration I assigned the output to a variable and printed it all at the end.

@ovs I managed to get 72 bytes by printing every iteration, thanks for the variable idea!

Python 2 version of print will give you 68 bytes

@DeadPossum Yeah, I know. Perhaps I'll switch to 2

Haskell, 63 bytes
unlines.map g.lines
g(x:r)|x<';',x>'/'=(' '<$['1'..x])++r
g s=s

Try it online! The first line is an anonymous function which splits a given string into lines, applies the function g to each line and joins the resulting lines with newlines. In g it is checked whether the first character x of a line is a digit. If this is the case, then ['1'..x] yields a string with length equal to the value of the digit x and ' '<$ converts the string into as many spaces. Finally the rest of the line r is appended. If x is not a digit we are in the second equation g s=s and return the line unmodified.

Java 8, 105 99 97 93 bytes
Saved few more bytes thanks to Nevay's suggestion,
s->{int i=s.charAt(0);if(i>47&i<58)s=s.substring(1);while(i-->48)s=" "+s;System.out.print(s);}

You have two bugs in your golfed version: The digit check has to use and instead of or; The brackets after the digit check are missing. Besides that you can save a few bytes by using s->{int i=s.charAt(0);if(i>47&i<58)for(s=s.substring(1);i-->48;s=" "+s);System.out.print(s);} (93 bytes).

@Nevay You are right. Thanks. I'll update my answer.

Japt (v2.0a0), 11 10 bytes
Japt beating Jelly and 05AB1E? That doesn't seem right!
r/^\d/m_°ç

Test it

Explanation
Implicit input of string U
r/^\d/m

Use Regex replace (r) all occurrences of a digit at the beginning of a line (m is the multiline flag - the g flag is enabled by default in Japt).
_

Pass each match through a function, where Z is the current element.
°

The postfix increment operator (++). This converts Z to an integer without increasing it for the following  operation.
ç

Repeat a space character Z times.
Implicitly output the resulting string.

Can m@ be shortened?

Not in this case, @Oliver; the m here is the multi-line flag for the regex, not the map method.

@Oliver: r/^\d/m_î (or r/^\d/m_ç) would be 2 bytes shorter but Z is a string so, unfortunately, it wouldn't work. r/^\d/m_°ç, for a 1 byte saving, does work, though :)

°ç is an amazing trick :-) I'd have suggested just \d for the regex, but that leaves out the flag... perhaps I should add support for flags on single-class regexes, like \dm (oh yeah, and that leaves out the ^ too...)

@ETHproductions, would it be feasible/possible to make the opening / optional in RegExes?

R, 138 128 bytes
-9 bytes thanks to CriminallyVulgar
n=readLines();for(d in grep("^[0-9]",n))n[d]=gsub('^.?',paste0(rep(' ',eval(substr(n[d],1,1))),collapse=''),n[d]);cat(n,sep='
')

This is pretty bad, but it's a bit better now... R is, once again, terrible at strings.
Try it online!

I am commenting on behalf of CriminallyVulgar, who suggests a 129-byte version, but does not have enough reputation to comment.

@Mr.Xcoder Thank you and @CriminallyVulgar!

123 Bytes Apparently rep can take a string of an int for the second argument???

@CriminallyVulgar huh. it's right there in the docs for rep, now that I check them again: "other inputs being coerced to an integer or double vector".

Cubically, 82 bytes
R3D1R1D1+0(?6{?7@7~:1+2<7?6{+35>7?6{:7-120?6{(B3@5B1-0)6}:0}}}?6!@7~-60=7&6+4-3=7)

Note: This will not work on TIO. To test this, use the Lua interpreter with the experimental flag set to true (to enable conditionals). There's currently a bug with conditional blocks on the TIO interpreter. When using the TIO interpreter, you should replace ?6! with !6 and &6 with ?6&, which keeps the byte count the same.
R3D1R1D1          Set the cube so that face 0 has value 1 and the rest of the values are easy to calculate

+0                Set the notepad to 1 so that it enters the conditional below
(                 Do
  ?6{               If the notepad is 1 (last character was \n or start of input)
    ?7@7              Output the current character if it's \n
    ~                 Get the next character
    :1+2<7?6{         If the input is >= '0'
      +35>7?6{          If the input is <= '9'
        :7-120            Set the notepad to the input - '0'
        ?6{               If the notepad isn't 0
          (                 Do
            B3@5              Output a space
            B1-0              Subtract 1 from notepad
          )6                While notepad > 0
        }                 End if
        :0              Set notepad to 1
      }                 End if
    }                 End if
  }                 End if

  ?6!@7             If the notepad is 0 (did not attempt to print spaces), print current character

  ~                 Get next character
  -60=7&6           If there is no more input, exit the program
  +4-3=7            Check if current character is \n, setting notepad to result
)                 Repeat forever

This isn't as short as the other Cubically answer, but I thought I'd give this a try anyway :D

What's going on with loops in the TIO interpreter?

@MDXF ) jumps to the most recent ( rather than the matching one I believe. EDIT: I'm in the chat.

@MDXF Maybe it was the conditional blocks, actually. I forgot, I'll update the answer. Regardless, they weren't matching up.

All right, I'll look at that later. I'm currently finishing Cubically 2.

@MDXF That's... really exciting to hear actually o_O

Jelly, 19 bytes
Ḣ⁶ẋ;µ¹µḣ1ẇØDµ?
ỴÇ€Y

Try it online!
-5 bytes total thanks to Jonathan Allan's comments and by looking at his post
Explanation
Ḣ⁶ẋ;µ¹µḣ1ẇØDµ?  Main link
             ?  Ternary if
                if:
       ḣ1       the first 1 element(s) (`Head` would modify the list which is not wanted)
         ẇ      is a sublist of (essentially "is an element of")
          ØD    "0123456789"
                then:
  ẋ             repeat
 ⁶              ' '
Ḣ               n times where n is the first character of the line (head)
   ;            concatenate the "beheaded" string (wording choice credited to Jonathan Allan)
                else:
     ¹          Identity (do nothing)
    µ µ     µ   Link separators
ỴÇ€Y            Executed Link
Ỵ               Split by newlines
  €             For each element,
 Ç              call the last link on it
   Y            Join by newlines

no need to swap arguments: Ḣ⁶ẋ;

The pop then head trick wont work if there is a line containing only a single digit character :(  -- ;0Ḣ would work for one byte, maybe there is a single atom, I also tried ¹, no joy there

@JonathanAllan Ah right. Thanks. ḣ1ẇØD works for the same bytecount \o/

ṚṪ will work :)

@JonathanAllan That works too :) But I made an explanation already for my method so I'm too lazy to change it :P But thanks anyway :)

Pyth,  16  15 bytes
jm.x+*;shdtdd.z

Try it online!

Explanation

jm.x+*;shdtdd.z   - Full program that works by reading everything from STDIN.

             .z  - Read all STDIN and split it by linefeeds.
 m               - Map with a variable d.
  .x             - Try:
     *;shd           - To convert the first character to an Integer and multiply it by a space.
    +     td         - And add everything except for the first character
            d        - If the above fails, just add the whole String.
j                 - Join by newlines.

Let's take an example that should be easier to process. Say our input is:
foo bar foo bar
1foo bar foo bar foo bar
2foo bar foo bar foo bar foo bar

The program above will do the following:

.z - Reads it all and splits it by newlines, so we get ['foo bar foo bar', '1foo bar foo bar foo bar', '2foo bar foo bar foo bar foo bar'].
We get the first character of each: ['f', '1', '2'].
If it is convertible to an integer, we repeat a space that integer times and add the rest of the String. Else, we just place the whole String. Hence, we have ['foo bar foo bar', ' foo bar foo bar foo bar', '  foo bar foo bar foo bar foo bar'].
Finally, we join by newlines, so our result is:

foo bar foo bar
 foo bar foo bar foo bar
  foo bar foo bar foo bar foo bar

Haha, we beat Jelly :)

V, 9 bytes
ç^ä/x@"é

Try it online!
Explanation
ç  /      ' On lines matching
 ^ä       ' (Start)(digit)
    x     ' Delete the first character
     @"   ' (Copy Register) number of times
       é  ' Insert a space

><>, 60 bytes
!^i:0(?;::"/")$":"(*0$.
v"0"-
>:?!v1-" "o
;>:o>a=&10&?.i:0(?

Try it online!
How It Works:
..i:0(?;... Gets input and ends if it is EOF
...
...
...

.^......::"/")$":"(*0$. If the inputted character is a digit go to the second line
...                     Else go to the fourth
...
...

....        If it was a digit
v"0"-       Subtract the character "0" from it to turn it into the corresponding integer
>:?!v1-" "o And print that many spaces before rejoining the fourth line
...

.^..               On the fourth line,
....               Copy and print the input (skip this if it was a digit)
....v              If the input is a newline, go back to the first line.
;>:o>a=&10&?.i:0(? Else get the input, ending on EOF

PHP, 83 chars
preg_replace_callback('/^\d/m',function($m){return str_repeat(' ',$m[0]);},$argv);

I think your code is not compliant with the input rules of this challenge, you should enclose this in a function with a $s  arg or populate it with the input. And it doesn't print anything

@LP154 is using argv acceptable?

@Petah If I'm correct in assuming argv is the command line args, then yes.

Gema, 21 characters
\N<D1>=@repeat{$1;\ }

Sample run:
bash-4.4$ gema '\N<D1>=@repeat{$1;\ }' <<< 'foo bar foo bar
> 1foo bar foo bar foo bar
> 2foo bar foo bar foo bar foo bar
>
> --------v
> 8|
> 8|
> 80
> 8,
> 7&'
foo bar foo bar
 foo bar foo bar foo bar
  foo bar foo bar foo bar foo bar

--------v
        |
        |
        0
        ,
       &