views:

404

answers:

4

I want split integers into their factors. For example, if the total number of records is:

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)

When it's more than 10k - I want everything on 1000 When it's more than 100k - I want everything on 10k

In this way I want to factor the number. How to achieve this? Is there any Perl module available for these kinds of number operations?

Suppose total number of records is 10k. It should be split by 1000x10 times only; not by 100 or 10s.

I can use sqrt function. But it's not always what I am expecting. If I give the input 146, I have to get (73, 2).

+2  A: 

If the number is not a prime you can use a factoring algorithm.

There is an example of such a function here: http://www.classhelper.org/articles/perl-by-example-factoring-numbers/factoring-numbers-with-perl.shtml

Andre Miller
Even if a number is prime you can use a factoring algorithm. You just don't get any additional factors. :)
brian d foy
That is true, but then the result would just be 1 x N, which I thought is not too useful to the original poster :).
Andre Miller
+2  A: 

You need to further explain this question to get a good answer.

Given an integer as input, what is the output that you want?

This should be a comment, not an answer, though I strongly agree
Ralph Rickenbach
+1  A: 

Loop through some common numbers in an acceptable range (say, 9 to 15), compute the remainder modulo your test number, and choose the lowest.

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];
}
Andrew Barnett
+5  A: 

You can use the same algorithms you find for other languages in Perl. There isn't any Perl special magic in the ideas. It's just the implementation, and for something like this problem, it's probably going to look very similar to the implementation in any language.

What problem are you trying to solve? Maybe we can point you at the right algorithm if we know what you are trying to do:

  • Why must numbers over 10,000 use the 1,000 factor? Most numbers won't have a 1,000 factor.
  • Do you want all the factors, or just the largest and its companion?
  • What do you mean that the sqrt function doesn't work as you expect? If you're following the common algorithm, you just need to iterate up to the floor of the square root to test for factors. Most integers don't have an integral square root.
brian d foy