欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

一个双射类,在给定自然数空间一对一完全映射,可逆运算,不可猜解

程序员文章站 2022-06-13 17:46:24
...
/**
 * 双射类
 * 在给定自然数空间一对一完全映射,可逆运算,不可猜解
 * @author liuxu
 *
 */
class Bijective
{
	static private $defaultPrime = '85310501873';//请使用个位为"3"、"7"、"9"的质数

	static public function getRandPrime()
	{
		return self::getMinPrime(rand(100000,900000)*100000+rand(100000,900000));
	}

	static public function getMinPrime($min)
	{
		$number = $min;
		while(true)
		{
			if(self::isPrime($number)) break;
			$number++;
		}

		return $number;
	}

	static public function isPrime($number)
	{
		$sqrt = intval(bcsqrt($number,0));
		for($i=2;$i<=$sqrt;$i++)
		{
			if(bcmod($number,$i)==='0')
			{
				return false;
			}
		}

		return true;
	}

	static public function mod($number,$len=10)
	{
		return bcmod(bcmul($number,self::$defaultPrime,0),bcpow(10,$len,0));
	}

	static public function loop($number,$len=8)
	{

		$min = $prev = $number;
		for($i=1;;$i++)
		{
			$next = self::mod($prev,$len);
			if($next==$number) break;
			$min = min($min,$next);
			$prev = $next;
		}

		$offset = ( $min % $i ) + 1;
		for($j=0;$j<$offset;$j++)
		{
			$number = self::mod($number,$len);
		}

		return $number;
	}

	static public function insanity($number,$len=10)
	{
		$number = self::mod($number,$len);
		$number = str_pad($number,$len,'0',STR_PAD_LEFT);

		$numberList = str_split($number,6);
		foreach($numberList as $key=>$value)
		{
			$numberList[$key] = str_pad(self::loop($value,strlen($value)),strlen($value),'0',STR_PAD_LEFT);
		}

		$number = implode('',$numberList);

		return $number;
	}

}