in reply to Re^2: Best way to make sure a number is an even multiple of another?
in thread Best way to make sure a number is an even multiple of another?
#!/usr/bin/perl use strict; use warnings; use Math::Big::Factors 'factors_wheel'; my $next = factor(100, 25); while ( my $factor = $next->() ) { print "$factor\n"; } sub factor { my ($target, $min) = @_; my @list = factors_wheel( $target ); my $by = $#list; my (%seen, @pos, @stop, $end_pos); my ($factor, $next, $continue) = (1, 1, 1); return sub { { $factor = 1; if ( $next ) { return () if ! $by || ! $continue; $continue = 0; @pos = (0 .. $by - 2, $by - 2); @stop = @list - $by .. $#list; $end_pos = $#pos; $by--; } my $cur = $end_pos; { if ( ++$pos[ $cur ] > $stop[ $cur ] ) { $pos[ --$cur ]++; redo if $pos[ $cur ] > $stop[ $cur ]; my $new_pos = $pos[ $cur ]; @pos[ $cur .. $end_pos ] = $new_pos .. $new_pos + +$by; } } $next = $pos[0] == $stop[0] ? 1 : 0; $factor *= $_ for @list[ @pos ]; $continue = 1 if $factor >= $min; redo if $seen{$factor}++ || $factor < $min; } return $factor; } }
Cheers - L~R
|
|---|