简体   繁体   中英

Is this algorithm reversible?

I have this algorithm written in PHP for my project:

<?php
$s = "abc"; //input -- string


$n = strlen($s);
$b = 0;
for ($i = 0; $i < $n; $i++)
{
$b += ord($s[$i]) * pow(31, ($n - ($i + 1)));
}


echo $b; //output -- int
?>

But now I have to reverse it to take the string from integer. I tried but it failed, is there any way to reverse it?

EDIT: By "any way" I meant that it doesn't have to reverse to the original text, but only to reverse to text that gives that value.

no, it's not...

easier example: let's assign every letter a value: a=1,b=2,c=3,d=4 etc...

and here we go: you have "5" - you don't know whether it is "ad" or "bba" or "bc" etc.

IF the string can be guaranteed to only have lowercase letters on it, it can; you'll have to figure out the maths for it (I suggest you work out in paper the algorithm, leaving the letters as variables; solve the equations and you'll see how to reverse it).

If the string is arbitrary, then no; because you're converting each character to a base-31 representation of the number, shifting it and adding the results -- however, this addition has lots of carries, so you can't work out the original characters just from the digits (that is, the final number) of the result.

EDIT: given your edit, then yes, it is possible. It can be a bit complicated, though -- i'll leave you to work out the maths yourself. Try juggling a bit with the number 31.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM