use strict; use warnings; my $n = <>; my %ms = (1=> 1); my @in = ([1, 1]); my @out; my $stp; for(1..$n){ for my $i(@in){ $stp = scalar(() = sprintf("%b", $i->[0]) =~ m/1/g); for my $j (-1, 1){ my @nxt = ($i->[0] + $j*$stp, $i->[1]+1); if(0 < $nxt[0] and $nxt[0] <= $n){ if(!defined($ms{$nxt[0]}) or $nxt[1] < $ms{$nxt[0]}){ $ms{$nxt[0]} = $nxt[1]; } push @out, \@nxt; } } } @in = @out; @out = (); } print defined $ms{$n} ? $ms{$n} : -1;