String hashing using 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 ; Given Strings
function polynomialRollingHash ( str ) { let p = 31 ; let m = ( 1e9 + 9 ) ; let power_of_p = 1 ; let hash_val = 0 ; for ( let i = 0 ; i < str . length ; i ++ ) { hash_val = ( hash_val + ( str [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) + 1 ) * power_of_p ) % m ; power_of_p = ( power_of_p * p ) % m ; } return hash_val ; } let str1 = " " ; let str2 = " " ; document . write ( " " + str1 + " " + polynomialRollingHash ( str1 ) ) ;