There is a bug in my program, its the factorization.
I am not factorizing well but it is not the cause of my WA as I added 'assert g == 1' after the factorization and no error was raised, so probably my factorization is good enough(?)
PS: for primes or for numbers whose factors are primes greater than sqrt(2**31) for ex 47497, my code gives wrong output. But I think no such test cases are present in the problem as it would raise an assertion error when 'assert g == 1' is placed after factorization.
EDIT: Thanks for the reply lakshman, I deleted that code and coded it again, it got AC.