#JavaScript, <s>93</s> 91 bytes n=>(g=x=>n-i?a[++x]|(h=(y,z)=>z?h(z,y%z):y)(x,c)<2?g(x):(a[c=x]=++i,x>n)+g(2):0)(a=[i=c=2]) [Try it online](https://tio.run/##FcPRCoMgFADQ9/5jcC9aNPcmu/oh4oO4MkfTqDFM9u@OHThP93GH3@P27lN@TG2mlkhBoEIq9VE7w1ixX1gITl6RVNULVH5eKsoToXCPd6EDFJTgjKdiibHIi0rIAgiUI4IjE8mTsNh8Tkdep2HNAUx34911/B87O7zcBjNi@wE)