이것은 내가 작성한 것입니다 (Java로 작성). 기본 아이디어는 32 비트 int를 2 개의 숫자로 나눕니다. 곱셈 효과를 포함한 이전 비트 합계. 하위 비트는 그 곱셈 효과를 추적합니다. 작동합니다. 그것은 (0, 1), (1, 0)과 같은 공통 인수에 대해서도 좋은 분배를가집니다.
public class AssociativelyMergedIntegers {
/** biggest unsigned 16-bit prime */
private static final int PRIME = 65521;
/** associative, not commutative hash function */
public static int merged(int first, int second) {
int firstFactor = remainderOf(first & 0x0000FFFF);
int secondFactor = remainderOf(second & 0x0000FFFF);
int firstSum = remainderOf(first >>> 16 & 0x0000FFFF);
int secondSum = remainderOf(second >>> 16 & 0x0000FFFF);
int resultSum = remainderOf(firstSum + (long) firstFactor * secondSum);
int resultFactor = remainderOf((long) firstFactor * secondFactor);
return resultSum << 16^resultFactor;
}
private static int remainderOf(long number) {
int rest = (int) (number % PRIME);
return rest == 0
? PRIME - 2
: rest;
}
}
(number mod prime)이 0 인 경우 remainderOf가 PRIME-2를 반환하는 목적은 무엇입니까? – supercat
목적은 인자의 인수가 0이면 resultFactor가 항상 0이되지 않도록하는 것입니다. 이렇게하면 임의의 숫자가 poison pill처럼 작동합니다. –