getting negative hash values

i am solving this on codeforces but i am getting WA evertime. am using hashing method and i think the reason is that for some substrings i am getting negative hash values. i think my method is correct but i dnt know where the source of error so someone please help me.

maybe your magic is beyond int limit which gives you negative numbers

yes it was due to i got the function for multiplying two large number mod a prime from topcoder and got AC. heres my code