math - Szudzik pairing not unique for two integers - Stack Overflow

admin2025-05-02  0

I have tried out an elegant pairing solution by Szudzik as an alternative to Cantors pairing, but there I have discovered that there are some cases where I get duplicates in Szudzik. Example:


function szudzikPair(x, y)
{
    return (x >= y ? (x * x) + x + y : (y * y) + x);
}

console.log(szudzikPair(
127382263,
10902761));

console.log(szudzikPair(
127382263,
10902759));

console.log(szudzikPair(
127382263,
10902760));

function cantorPair(x, y) 
{
    return (0.5 * (x + y) * (x + y + 1)) + y;
}

console.log(cantorPair(
127382263,
10902761));

console.log(cantorPair(
127382263,
10902759));

console.log(cantorPair(
127382263,
10902760));

The szudzik pair returns the same integer in all three cases.

I expected Szudzik algorithm work the same way as Cantor, and return a unique integer

My Output>

16226241065286192
16226241065286192
16226241065286192
9561374011385560
9561373734815512
9561373873100536

I have tried out an elegant pairing solution by Szudzik as an alternative to Cantors pairing, but there I have discovered that there are some cases where I get duplicates in Szudzik. Example:


function szudzikPair(x, y)
{
    return (x >= y ? (x * x) + x + y : (y * y) + x);
}

console.log(szudzikPair(
127382263,
10902761));

console.log(szudzikPair(
127382263,
10902759));

console.log(szudzikPair(
127382263,
10902760));

function cantorPair(x, y) 
{
    return (0.5 * (x + y) * (x + y + 1)) + y;
}

console.log(cantorPair(
127382263,
10902761));

console.log(cantorPair(
127382263,
10902759));

console.log(cantorPair(
127382263,
10902760));

The szudzik pair returns the same integer in all three cases.

I expected Szudzik algorithm work the same way as Cantor, and return a unique integer

My Output>

16226241065286192
16226241065286192
16226241065286192
9561374011385560
9561373734815512
9561373873100536
Share Improve this question asked Jan 2 at 12:18 Barbara EpifanovaBarbara Epifanova 1 1
  • 1 If this is javascript, and BigInt is supported (support is very wide now) you want to use BigInts instead of numbers, which in practice means to add an n after each integer literal, i.e., szudzikPair(127382263n, 10902761n); for that to work with cantorPair you'll have to change the 0.5 * formula with a division by 2. – kikon Commented Jan 3 at 15:42
Add a comment  | 

1 Answer 1

Reset to default 1

I suppose this is JavaScript, maybe using NodeJS, or directly in a browser.

The max integer number for which you can add 1 and the result is not the same value that you used in the operation is Number.MAX_SAFE_INTEGER.

After that, integer numbers have "gaps" in their representation. So what I believe is happening, is that you are over the max number and thus get the same result because those numbers cannot be represented with enough precision.

Check the specs for reference to this.

转载请注明原文地址:http://anycun.com/QandA/1746120886a91957.html