The primorial \$p_n\#\$ is the product of the first \$n\$ primes. The sequence begins \$2, 6, 30, 210, 2310\$.
A Fortunate number, \$F_n\$, is the smallest integer \$m > 1\$ such that \$p_n\# + m\$ is prime. For example \$F_7 = 19\$ as:
$$p_7\# = 2\times3\times5\times7\times11\times13\times17 = 510510$$
Adding each number between \$2\$ and \$18\$ to \$510510\$ all yield composite numbers. However, \$510510 + 19 = 510529\$ which is prime.
Let us generalise this to integer sequences beyond primes however. Let \$\Pi(S,n)\$ represent the product of the first \$n\$ elements of some infinite sequence \$S\$. All elements of \$S\$ are natural numbers (not including zero) and no element is repeated. \$S\$ is guaranteed to be strictly increasing.
In this case, \$p_n\# = \Pi(\mathbb P,n)\$. We can then define a new type of numbers, generalised Fortunate numbers, \$F(S,n)\$ as the smallest integer \$m > 1\$ such that \$\Pi(S,n) + m \in S\$.
You are to take an integer \$n\$ and an infinite sequence of positive integers \$S\$ and output \$F(S,n)\$.
You may take input in any reasonable representation of an infinite sequence. That includes, but is not limited to:
- An infinite list, if your language is capable of handling those (e.g. Haskell)
- A black box function which returns the next element of the sequence each time it is queried
- A black box function which returns two distinct values to indict whether it's argument is a member of that sequence or not
- A black box function which takes an integer \$x\$ and returns the \$x\$th element of the sequence
If you have another method you are considering using, please ask in the comments about it's validity.
This is code-golf so the shortest code in bytes wins
Examples
I'll walk through a couple of examples, then present a list of test cases below.
\$n = 5, S = \{1, 2, 6, 24, 120, ...\}\$
Here, \$S\$ is the factorials from 1. First, \$\Pi(S, 5) = 1\times2\times6\times24\times120 = 34560\$. We then find the next factorial greater than \$34560\$, which is \$8! = 40320\$ and subtract the two to get \$m = 40320 - 34560 = 5760\$.
\$n = 3, S = \{6, 28, 496, 8128, ...\}\$
Here, \$S\$ is the set of perfect numbers. First, \$\Pi(S, 3) = 6\times28\times496 = 83328\$. The next perfect number is \$33550336\$, so \$m = 33550336 - 83328 = 33467008\$
Test cases
n
S
F(S, n)
5
{1,2,6,24,120,...} (factorials)
5760
3
{6,28,496,8128,...} (perfect numbers)
33467008
7
{2,3,5,7,11,...} (prime numbers)
19
5
{1,3,6,10,15,...} (triangular numbers)
75
Any n
{1,2,3,4,...} (positive integers)
2
9
{1,4,9,16,25,...} (squares)
725761
13
{4,6,9,10,14,...} (semiprimes)
23