1 RSHash
1 /* 【算法】RSHash(因Robert Sedgwicks在其《Algorithms in C》一書中展示而得名)
2 * 【說明】63689和378551都是質數,之所以取這兩個數,我想是因為抗碰撞小(散列分布均勻)
3 * 【時間】祁俊輝->2017.5.17
4 * */
5 public class RSHash {
6 //RSHash算法
7 static long RS_Hash(String str){
8 int a=63689;
9 int b=378551;
10 long hash=0;
11 for(int i=0;i<str.length();i++){
12 hash=hash*a+str.charAt(i);
13 //System.out.println(hash);
14 a=a*b;
15 //System.out.println(a);
16 }
17 return (hash & 0x7FFFFFFF);//32位
18 //return (hash & 0x7FFFFFFFFFFFFFFFL);//64位
19 }
20 //主函數
21 public static void main(String[] args) {
22 System.out.println(Long.toBinaryString(RS_Hash("祁俊輝")));
23 }
24 }
2 BKDRHash
1 /* 【算法】BKDRHash(Java字符串類的Hash算法,累成因子取31)
2 * 【說明】累成因子可以為31/131/1313/13131/131313...
3 * 【時間】祁俊輝->2017.5.17
4 * */
5 public class BKDRHash {
6 //BKDRHash算法
7 static long BKDR_Hash(String str){
8 long seed=131;
9 long hash=0;
10 for(int i=0;i<str.length();i++){
11 hash=hash*seed+str.charAt(i);
12 //System.out.println(hash);
13 }
14 return (hash & 0x7FFFFFFF);//32位
15 //return (hash & 0x7FFFFFFFFFFFFFFFL);//64位
16 }
17 //主函數
18 public static void main(String[] args) {
19 System.out.println(Long.toBinaryString(BKDR_Hash("祁俊輝")));
20 }
21 }
3 DJBHash
1 /* 【算法】DJBHash(目前公布最有效的Hash算法)
2 * 【說明】俗稱"Times33"算法
3 * 【時間】祁俊輝->2017.5.17
4 * */
5 public class DJBHash {
6 //DJBHash算法
7 static long DJB_Hash(String str){
8 long hash=5381;
9 for(int i=0;i<str.length();i++){
10 hash=((hash<<5)+hash)+str.charAt(i);
11 //System.out.println(hash);
12 }
13 return (hash & 0x7FFFFFFF);//32位
14 //return (hash & 0x7FFFFFFFFFFFFFFFL);//64位
15 }
16 //主函數
17 public static void main(String[] args) {
18 System.out.println(Long.toBinaryString(DJB_Hash("祁俊輝")));
19 }
20 }
4 JSHash
1 /* 【算法】JSHash(由Justin Sobel發明的一種hash算法)
2 * 【說明】位操作
3 * 【時間】祁俊輝->2017.5.18
4 * */
5 public class JSHash {
6 //JSHash算法
7 static long JS_Hash(String str){
8 long hash=1315423911;
9 for(int i=0;i<str.length();i++){
10 hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2));
11 //System.out.println(hash);
12 }
13 return (hash & 0x7FFFFFFF);//32位
14 //return (hash & 0x7FFFFFFFFFFFFFFFL);//64位
15 }
16 //主函數
17 public static void main(String[] args) {
18 System.out.println(Long.toBinaryString(JS_Hash("祁俊輝")));
19 }
20 }
5 SDBMHash
1 /* 【算法】SDBMHash
2 * 【說明】與BKDRHash思想一致,只是數乘因子不同
3 * 【時間】祁俊輝->2017.5.18
4 * */
5 public class SDBMHash {
6 //SDBMHash算法
7 static long SDBM_Hash(String str){
8 long hash=0;
9 for(int i=0;i<str.length();i++){
10 hash=hash*65599+str.charAt(i);
11 //hash=str.charAt(i)+(hash<<6)+(hash<<16)-hash;
12 //System.out.println(hash);
13 }
14 return (hash & 0x7FFFFFFF);//32位
15 //return (hash & 0x7FFFFFFFFFFFFFFFL);//64位
16 }
17 //主函數
18 public static void main(String[] args) {
19 System.out.println(Long.toBinaryString(SDBM_Hash("祁俊輝")));
20 }
21 }