getting negative hash values

i am solving this Problem - 182D - Codeforces 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 overflow.so i got the function for multiplying two large number mod a prime from topcoder and got AC. heres my code Submission #6750190 - Codeforces