我在Lua 5.3中正确地实现了这个算法吗?


-- (1451AFBx - 1A7D575) ^ (-1C6B438x + i)
-- y = ( Ax + B )^( Cx + D )
-- x0 = B0 ^ D0 ^ y0
math.randomseed( os.time( ) );
local UINT32_MAX = 2^32 - 1;
local A = 0x1451AFB
local B = -0x1A7D575;
local C = -0x1C6B438;
local D =  math.random( 0, UINT32_MAX );
local x = math.random( 0, UINT32_MAX );
local y = bit32.bxor( A * x + B, C * x + D );
x = { };
local function printf( msg, ... )
    print( string.format( msg, ... ) );
end
local function getBit( n, i )
    return ( ( n & ( 1 << ( i - 1 ) ) ) > 0 ) and 1 or 0;
end
for i = 1, 32 do
    table.insert( x, 1, math.floor( bit32.bxor( getBit( B, i ), getBit( D, i ), getBit( y, i ) ) ) );
end
x = tonumber( table.concat( x ), 2 );
local y2 = bit32.bxor( A * x + B, C * x + D );
assert( y ==  y2,  string.format( 'Invalid solution: %u ~= %u', y, y2 ) );
printf( 'x = %u', x );

Lua解释器的输出:

input:33: Invalid solution: 3996422455 ~= 2979830783

上面的算法是基于我在数学StackExchange上收到的答案。在我奖励答案之前,我想确保他描述的算法确实有效。然而,似乎我的断言总是失败。是他的算法错了,还是我的代码错了?

我刚刚意识到我犯了一个愚蠢的错误。

这个算法

:

for i = 1, 32 do
    table.insert( x, 1, math.floor( bit32.bxor( getBit( B, i ), getBit( D, i ), getBit( y, i ) ) ) );
end

基本上混淆了:

x = bit32.xor( B, D, y );

但这显然不是他的本意。

替换上述for循环代码段的实际代码如下:

local b = B;
local d = D;
for i = 1, 32 do
    table.insert( x, 1, math.floor( bit32.bxor( getBit( b, 1 ), getBit( d, 1 ), getBit( y, i ) ) ) );
    b = ( A * x[1] + b ) // 2;
    d = ( C * x[1] + d ) // 2;
end

代码现在传递断言。

最新更新