本帖最后由 523066680 于 2019-3-29 17:12 编辑
提速,在递归排列的每一层都做重复数的排查。
细节,例如当前累积到3位数,133*133 = 17689,那么只判断 689 是否与 133重合,而不考虑 17,因为 17 可能受到高位数的影响而变化。- use Time::HiRes qw/time/;
- my $ta = time();
- our $maxlen = 6;
- permute([], [0..9], 0);
-
- printf "time usage: %.2fs\n", time() - $ta;
-
- sub permute
- {
- my ($a, $b, $lv) = @_;
-
- return if $lv > $maxlen;
- if ( $lv > 0 and $a->[0] != 0 )
- {
- my $n = join("", @$a);
- my $mp = $n*$n;
- $mp = substr($mp, -$lv) if ($lv < $maxlen);
- for ( 0 .. $#$a ) { return if $mp =~ $a->[$_] }
- if ($lv == $maxlen)
- {
- printf "%d %d\n", $n, $mp;
- return;
- }
- }
-
- for ( 0 .. $#{$b} ) {
- permute( [ $b->[$_], @$a ] , [@{$b}[0..$_-1, $_+1..$#$b]], $lv+1);
- }
- }
复制代码 639172 408540845584
203879 41566646641
time usage: 0.05s |