more efficient way of calculation hash index

I'm working on a program that will accept a string and then return the hash value similar to the formula in java.lang.String.hashCode():

str[0] *(31^(n-1))+ str[1] * (31(n-2)) +....... str[n-1]

I've been instructed not to use the built in pow() function so I just wrote my own. Here's the code I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

int myPow(int number, int n)
{
	if(n == 0)
		return 1;
	else {
		return (number * myPow(number, n-1));
	}

}

unsigned int hashmap::hashStr(char const * const str)
{
	unsigned int hash = 0;
	int n = strlen(str);
	for(int i = 0; i < n; i++)
	{
		int x = ((n-1)-i);
		hash += static_cast<int>(str[i])*myPow(32, x);
	}
	return hash;
}


I think there's a better way to do this without writting the pow function and using recursion, probably by factoring out the equation but I'm lost as to how I would do that.
You don't need recursion to calculate pow():
1
2
int result = 1;
for(int i = 0; i < n; i++) result *= number;


Also, since all powers form a progression, you could simply add the calculation in your for loop:
1
2
3
4
5
6
7
8
9
unsigned int hash = 0;
int n = strlen(str);
int pow = 1;
for(int i = 0; i < n; i++){//you may want to make this i=n-1; i>= 0; i--
//it doesn't make any real deference though.
	pow *= 31;
	hash += static_cast<int>(str[i])*pow;
}
return hash;
Topic archived. No new replies allowed.