#JavaScript, <s>93</s> <s>91</s> 87 bytes

Throws an overflow error for `0` or `1`, outputs `0` for `2`.

    n=>(g=x=>n-i?g[++x]|(h=(y,z)=>z?h(z,y%z):y)(x,c)<2?g(x):(g[c=x]=++i,x>n)+g(2):0)(i=c=2)

[Try it online](https://tio.run/##Dc3RCsIgFADQX@mh4F50Euup0XX0DT2ukWJlxtLhRuiqb1/7gXOe@q0HE10/Fj5cb/OdZk8SLCWSvnC1bRhL7RceBJlPSHKqHzDxvJmwygiJGzyUtYWEFdjGUGqJMceT9MgslFhtERwZKnE2wQ@hu4kuWGiEEMcYdYb9Hlvx0j3AhafFV@tPYlT@lOj19TTqOMIOmVqRXCl2Xx4Uz@C8OnuF8x8)