Need help in another approach to solve ISS

I need some help in optimizing my code for the problem ISS(interesting sequence) MAY long challenge. I have used some different approaches compared to the one in the official editorial. Rather than calculating gcd, I analyzed the gcd array for some K values coming up with some pattern that when 4K+1 is prime the answer will be 6K and for the rest, the gcd array(i.e array containing gcd of consecutive terms of the sequence ) will contain only 1s and other numbers which are factors of 4*K+1.So we just need to find how many times the factors are appearing in the gcd array.
I have matched answers with the brute force approach and it’s all fine but getting TLE . Is there any way to optimize my code?
I am adding my submission -ISS