Search code examples
perlintegerfactors

How do I factor integers using Perl?


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).


Solution

  • 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.