#JavaScript, <s>93</s> 91 bytes Throws an overflow error for `0` or `1`, outputs `0` for `2`. 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/##Dc1LDoIwEADQq7jQZCatjcEVxCnxDC6R2En5WKMtAWIK6tmRd4H34DcPtnfduPehqpeGFk8aWoqk/d7lXAgRyy/cCSY5I@k5v8Msp92M2YQQpcVTkrcQMQMuLMWShHAyao@ihQSzAwJT4chSUuJigx/Cs1bP0EKhlDr3PU@QpliqF3cANxnXw2w/UVDyM6rj6jJyP8IRhdmQ3hjRrBeqR3DeXL3B5Q8)