String hashing using Polynomial rolling hash function | Java implementation of the Polynomial Rolling Hash Function ; Function to calculate the hash of a String ; P and M ; Loop to calculate the hash value by iterating over the elements of String ; Driver Code ; Given Strings
class GFG { static long polynomialRollingHash ( String str ) { int p = 31 ; int m = ( int ) ( 1e9 + 9 ) ; long power_of_p = 1 ; long hash_val = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { hash_val = ( hash_val + ( str . charAt ( i ) - ' a ' + 1 ) * power_of_p ) % m ; power_of_p = ( power_of_p * p ) % m ; } return hash_val ; } public static void main ( String [ ] args ) { String str1 = " geeksforgeeks " ; String str2 = " geeks " ; System . out . print ( " Hash ▁ of ▁ ' " + str1 + " ' ▁ = ▁ " + polynomialRollingHash ( str1 ) ) ; } }