#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/##Dc1BDoIwEADAr3jQZDctjcGLErfEN3hEYjcFoURbgsQU1Lej84Hp@MVPO7h@THyo6uVGiycNDUXSPnE5F0LE8gMtwSRnJD3nLcxy2syYTQhRWjymeQMRM@DCUixJCCej9igaSDHbIjAVjiylJS42@Ge41@oeGiiUUqdh4AkOeyzVg3uAq4z/w6zfUdDua1TP1XnkYYQdCrMivTLi9r9QdcF5c/EGlx8)