代码之家  ›  专栏  ›  技术社区  ›  joe

如何使用Perl对整数进行因子运算?

  •  -5
  • joe  · 技术社区  · 16 年前

    169 - ( 13 x 13 times) 
    146 - ( 73 x 2 times) 
    150 - ( 50 x 3 times)
    175 - ( 25 x 7 times)
    168 - ( 84 x 2 ) 
    160 - ( 80 x 2 times) 
    

    当它超过10000时,我希望一切都在1000

    假设记录总数为10k。它应该只被分割1000x10倍;不是100秒或10秒。

    sqrt 功能。但这并不总是我所期待的。如果我给出输入146,我必须得到(73,2)。

    3 回复  |  直到 16 年前
        1
  •  5
  •   brian d foy    16 年前

    • sqrt函数不能按预期工作是什么意思?如果你遵循通用算法,你只需要迭代到平方根的底部来测试因子。大多数整数没有整数平方根。
        3
  •  1
  •   Andrew Barnett    16 年前

    在可接受的范围内(比如9到15)循环一些常见的数字,计算余数模你的测试数,然后选择最小的。

    sub compute_width {
        my ($total_records) = @_;
        my %remainders;
        for(my $width = 9; $width <= 15; $width += 1) {
          my $remainder = $total_records % $width;
          $remainders{$width} = $remainder;
        }
        my @widths = sort { 
          $remainders{$a} <=> $remainders{$b} || 
          $a <=> $b 
        } keys %remainders;
        return $widths[0];
    }