getting negative hash values

i am solving this http://codeforces.com/problemset/problem/182/D 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 http://codeforces.com/contest/182/submission/6750190

//