[Question]
  [
[Lucky numbers](https://en.wikipedia.org/wiki/Lucky_number) ([A000959](https://oeis.org/A000959)) are numbers generated by applying the following sieve:
Begin with the list of natural numbers:
```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, ...
```
Now, remove every second element (\$n = 2\$, the smallest element in the list aside from 1):
```
1,    3,    5,    7,    9,     11,     13,     15,     17,     19,     21,     23,     25, ...
```
Now, remove every third element (\$n = 3\$, the next remaining element after 2):
```
1,    3,          7,    9,             13,     15,             19,     21,             25, ...
```
Now, remove every seventh element (\$n = 7\$, the next remaining element after 3):
```
1,    3,          7,    9,             13,     15,                     21,             25, ...
```
Then continue removing the \$n\$th remaining numbers, where \$n\$ is the next number in the list after the last surviving number. Next in this example is 9, then 13 and so on.
Eventually, this converges to the lucky numbers:
```
1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, 87, 93, 99, ...
```
---
However, we've already [looked at](https://codegolf.stackexchange.com/q/45785/66833) the lucky numbers. Today, we'll be looking at a related sequence: the lucky factors ([A264940](https://oeis.org/A264940)). These are the values of \$n\$ that remove a specific integer \$x\$.
For example, \$x = 2\$ is removed when \$n = 2\$, so \$2\$'s lucky factor is \$2\$  
Additionally, \$x = 19\$ is removed when \$n = 7\$, so \$19\$'s lucky factor is \$7\$
If \$x\$ is lucky, its lucky factor is \$0\$.
The first 50 elements of this sequence are
```
0, 2, 0, 2, 3, 2, 0, 2, 0, 2, 3, 2, 0, 2, 0, 2, 3, 2, 7, 2, 0, 2, 3, 2, 0, 2, 9, 2, 3, 2, 0, 2, 0, 2, 3, 2, 0, 2, 7, 2, 3, 2, 0, 2, 13, 2, 3, 2, 0, 2
```
---
This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. You may choose to:
* Take a positive integer \$x\$ and output the lucky factor of \$x\$
* Take a positive integer \$x\$ and output the lucky factors of each integer \$1 \le i \le x\$
* Output the infinite list of lucky factors
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
---
## Test cases
```
 x  n
15  0
57  9
26  2
41  3
50  2
13  0
48  2
20  2
19  7
22  2
24  2
27  9
60  2
54  2
49  0
 2  2
 7  0
45 13
55 15
```
  
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
Takes a positive integer \$ x \$ and outputs the lucky factor of \$ x \$. Outputs via exit code.
```
x=input()
R=range(1,x+1)
for i in R:i+=i<2;del R[i-1::i];x>R[-1]<exit(i)
```
[Try it online!](https://tio.run/##TZBPj4IwFMTv/RRzMaURiUXQFWVve9ib4Wo8sFDXJlIaKBE/PduW/XdpXmbmTX95@mlurYqnqq0FclBKpzGXSg8mYKTIu1J9ioCH45Izcm07SEiFIpPLXB7jQy3uKM5yxbNMXg7ja3Fe8ctRjNIEkk22jBDZ6LYz6IcP3bWV6Ptf5dkT8pDmhlYLFVBHEOknDUEflKHscc0IcI0enTQicDazdUp7TA9zl0o4HlsV9aaWyi6MIZRNNKUOpDKhz0S9vlskxgi@9xc1xQIjgYOywh9edPI4Z6rnyzieH7RLCP9N/j/@fnpjc09UtU0zKFmVltff0F3SmxZljnTCDJ2ar51DTTwF1iTdAXsSb4GYJBzYkHTtZr5xbvLi5nhW9sCOxLFXEv/63a13U68ke7cFn8HON6TgttO@6Rc "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~75~~ ~~73~~ ~~71~~ 63 bytes
```
x=scan();a=b=1:x;while(x%in%a)a=a[-b*(T=c(a,0)[F<-F+1]+!T-1)];T
```
[Try it online!](https://tio.run/##VcqxCoMwEADQvV9xpYh31YAZuhiz@gXZrMMZDA2UKNFioPTbUzp2fbyYHXQC3CvY3S8BE8EbNsvhTynBxczbDkfkdZ1jTvp3kBTrScs2qePhnzOmwoeCiTUPYrqi0Ra5bmjoO9FXcqzORkgalcmfk1sievABZHtryPKOvgaHnmoo76Gk/AU "R – Try It Online")
Returns the \$n\$-th lucky factor.
Thanks for -2 bytes to Giuseppe and -8 bytes to Dominic van Essen.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 27 bytes
```
2ịŻ‘ɼ»2$‘¤ị,ḟm¥@¥ƊƲƬṪċ¥Ðḟ⁸Ḣ
```
[Try it online!](https://tio.run/##JYwxCsJAFET7PcUUlgrJmjUGQTyF4AFsRK0stIs2AW0sBRVBTKFYichKrDYa8Bi7F1l/1mZ4vP9nBv3hcGYt19nqk5l4832pjFcI1IlUVcvDSKUdlRbL4lZc9fPyXqk0X5M3c6nl0XrqrJ/blol3qLVh4n0rT5jO7hOzuJr5Q8sbQVfLJT0T5QlFz1pMgTHzBeAxEQIR4w2As8AH6kx4Jfv18ho0S@Z/EwEh49yZwKXrNtxVOBNEZQvuB6FbEPBpk1L8AA "Jelly – Try It Online")
A full program taking an integer as its argument and printing an integer. Could almost be used as a monadic link, but the register needs to be reset to zero before each call. The TIO link has a footer that runs all of the test cases.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~73~~ 67 bytes
```
i=1
f@n_:=0Module[{k=++i},f@_/;n∣k++=n]
Print@f@Max[,2]~Do~{,∞}
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/T1pArzSEv3srWwDc/pTQnNbo621ZbO7NWJ80hXt8671HH4mxtbdu8WK6Aosy8Eoc0B9/Eimgdo9g6l/y6ap1HHfNq//8HAA "Wolfram Language (Mathematica) – Try It Online")
Prints lucky factors indefinitely.
`f` is designed to be called on consecutive natural numbers, starting with `2,2,3,4...`.
Initially there is only one rule defined for `f`, a generic definition which is called only when `n` is lucky. It returns 0, and adds a new, more specific definition: a sieve which returns `n` every `n`th it's called.
Mathematica tries more specific definitions before more general ones. When rules have the same generality (as will be generated by the lucky numbers), they're tried in order of definition. Thus a sieve is only attempted if earlier ones did not filter that number.
---
### ~~69~~ ~~67~~ 69 bytes
```
Array[Clear@f;f[i=1]=f@2;f@n_:=0Module[{k=++i},f@_/;n∣k++:=n];f,#]&
```
[Try it online!](https://tio.run/##FYzRCoIwFIbv9xpCFFuktlkpi0W3BUGXQ2SYM1EX2LoI0eveozfrRdbx4ud8fOfnb5W9F62yVa5cyd2h69RbHptCdUInWlY8SLkWYaKFyWLunx@3V1PIvuYYVwPRIlsl5vf51hjH3KSJJl46c5euMlZ6y/38pJ5WAHizhSgF/MZrrszYo4ARxDYEhRFBNAD2CQrWwFtwE@/ghhAKgV4EjgHTyRMEhk4LDA3uDw "Wolfram Language (Mathematica) – Try It Online")
Function which returns the lucky factors of `1..x`.
[Answer]
# [Python 2](https://docs.python.org/2/), 143 bytes
```
def f(x):
	m=1;n=range(1,x+1)
	while x in n and max(n)>m:m=min(q for q in n if q>m);n=[q for i,q in enumerate(n)if-~i%m]
	print 1-(x in n)and m
```
[Try it online!](https://tio.run/##JU7LbsIwEDzHXzGXSrYaEDYxaajCV/RWVVUkHLCEF8ckIlz666ntXHZXMzsP/xqvd1LLcjY9ej6LIytcKz@pDR1dDJfl/C4FK55XezOYYQmEjs5w3cxJnNzRtc4SH9DfA4aVtz2GkxPR5HvFbZkZQ5MzoRtNVNp@82ff3A8rfLA0Qm746i6y@7IGfoXJxEZziRfamOl5/C0RuuevJT@NXGwf/mbjjh1T/UVqYMd0DTRMHQDFKgnsmd6lW@4TW32kW61IA9RMqYxUeWbtIbM6I1WTVMg/qLODhoyecep/ "Python 2 – Try It Online")
a very unintelligent and trivial implementation of this
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 69 bytes
```
f=lambda n,k=2:n>=k and(f(n+n//k*~-t,k+1)if(t:=k>2<=f(k))+n%k else k)
```
[Try it online!](https://tio.run/##NY7BbsMgEETP4Sv2YpmNSROwiWOr@F9c2SgIh6KYKsqlv@6GQC/7doZhwD/D9dvVF3/fNq2W8fY1jeCYVaJ3g7Iwuolq6ip3PNr97yEwW3E0moZe2UF8Kk0tYuUKC/OyzmBxe1zNMgPvyc6wWd1GT40LzDj/Eyh@rH4xgZZwGKBEJDt/f53SshATqAEKuUJZUMM0NYjvqdSMG5fxwonINrIj4hwpSMMjayJPSfM65ZpL0uLf7yJbIkT2m8zcd845mf2mSz2Q89Dm3vc/@OvBtMg/ "Python 3.8 (pre-release) – Try It Online")
Direct recursion. Returns the lucky factor of `x`, using `False` instead of `0`.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 107 bytes
```
x->{int s[]=new int[x+1],i=1,j,c;for(;++i<x;)for(c=j=s[i]<1?0:x;j++<x;)s[j]+=s[j]<1&&++c%i<1?i:0;return s;}
```
[Try it online!](https://tio.run/##NY87b4MwEMf3fIpTJCJSEwvULcbpVqlDp4yIweWRnEsMso@UKMpnp3ZKB9/Dv/@9tLqqna6/Z7wMvSXQPucjYcfb0VSEveEvYlV1yjn4VGjgvgIYxq8OK3CkyLtrjzVcPIuPZNGcihKUPbntUwrwYeh9aZWjoaI8QAtynnaHu0/BFaU0zQ8ENLGsTFBmiU4q0fY2FoxhPoltiCuppSuwzLO3dD8JzVggrtAlk8Hm2WbDWBWhF@A@Fbah0Rpw4jGL5yJXZcE2buwIJLRcDUN3i7M03f7hMCNI0NNMeJcvat415kRn/8XY/1EAx5uj5sL7kfjgr6Y2Xkev9R6iOjLrBDBZqv3Gy4DHKrzH/As "Java (JDK) – Try It Online")
* This outputs the lucky factors of each integer \$1 \le i \le x\$ in a 0-indexed array, but the mapping basically stays `result[x] = factor` (plus has `result[0] = 0`, which shouldn't be taken into consideration).
### Explanation
This answer basically counts the number of zeroes, and every "lucky"-th zero is changed into the current lucky factor.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepade)
```
L∞IFD®LKн©ôD€θI£®‚ˆ€¨˜}I£ILå≠÷¯vy`¸Þ‡
```
It's slow, ugly, and long, but it works.. :/ I might try to revisit this one from scratch later on.
Given an input \$n\$, outputs the first \$n\$ values.
[Try it online.](https://tio.run/##AU0Asv9vc2FiaWX//0ziiJ5JRkTCrkxL0L3CqcO0ROKCrM64ScKjwq7igJrLhuKCrMKoy5x9ScKjSUzDpeKJoMO3wq92eWDCuMOe4oCh//8yMA)
**Explanation:**
```
L                   # Push a list in the range [1, (implicit) input]
 ∞                  # Push an infinite positive list: [1,2,3,...]
  IF                # Loop the input amount of times:
    D               #  Duplicate the infinite list
     ®L             #  Push a list in the range [1,`®`]
                    #  (`®` is -1 by default, so the first iteration is [1,0,-1])
       K            #  Remove these values from the duplicated infinite list
        н           #  Pop and only leave the first (smallest) value
                    #  (this is basically the smallest value above `®` (and 1))
         ©          #  Store it as new `®` (without popping)
          ô         #  Split the infinite list into parts of that size
           D        #  Duplicate this list of parts
            €θ      #  Only leave the last value of each part
              I£    #  Only keep the first input amount of values of this infinite list
                ®‚  #  Pair it with `®`
                  ˆ #  And pop and add it to the global array
            €¨      #  Remove the last value from each part
              ˜     #  And flatten the list
   }I£              # After the loop: only leave the first input amount of values
      IL            # Push a list in the range [1,input]
        å≠          # Check for each that it's NOT in this list
          ÷         # Integer-divide the initial [1,input] list by these 0s/1s,
                    # where division-by-0 results in 0
                    # (this basically mapped all Lucky numbers to 0s)
    ¯               # Push the global array
     vy             # Loop over each pair `y`:
       `            #  Pop and push the list and integer separated to the stack
        ¸Þ          #  Create an infinite list only containing this integer
          ‡         #  Transliterate all values in the list to the integer in our list
                    # (after which the list is output implicitly as result)
```
[Answer]
# [Dart](https://www.dartlang.org/), 151 143 138 bytes
```
f(x)=>([n,c,i,s]){for(s=[for(;i<x;)++i];n<s.last;i=s.length)for(n=s[c];i>0;c=s[i]>n?i:c)if(i--%n<1&&s.removeAt(i)==x)return n;}(0,1,0)??0;
```
[Try it online!](https://tio.run/##PY9NboMwEIX3nGI2jWzFQUAgNBgT9QA9QcQCOaYdNTGR7aBEUc5OgeJuPJ/ee56fU2PcMLTkTkVFjppJhszW9Nl2hlhxnArH8s7peo0116UNz411HMUISn@5bzpFtLBHWXOsIi5HxLrSBywkxZbgZvOmy3i1sqFRl65XH44gFeJOjXI3o0HzF4lYzCJ6OER8kJ22Dj6ba4naMRifCmRjlQUBzwAgzgqI2AhZXsB@gmRXQDJBGhewna1oUeLtEk7fFyX5t/YF5LOSeCv14DvvfDjzVrpfGoL/BbkfMS4W/42fKGPBiwdB3@EJLg1qQuf1r2a8iMwHhUo7g1PtlXkQIimICloiwx/1GFmADPvmfFOU8uA1/AI "Dart – Try It Online")
Takes a positive integer `x` and output the lucky factor of `x`. I tried to reduce this as much as possible since Dart is a little verbose and that's the best I could come with.
Ungolfed:
```
int f(int x) {
  int c = 1;
  var s = [for(int i = 1; i <= x; i++) i];
  for (int n = 0; n < s.last;) {
    n = s[c];
    for (int i = s.length; i > 0; --i) {
      if ((i + 1) % n == 0) {
        if (s.removeAt(i) == x)
          return n;
      }
      if (s[i] > n) c = i;
    }
  }
  return 0;
}
```
]