Find all the integers multiplied gives X?

If I have a number, say 12, how can I calculate all the integers that multiply will give 12?

Example: if 12, then the solution will be 1x12, 2x6, 3x4.

How to do it?

+3
source share
2 answers

Christian Works For brute force, to be more elegant, try to implement some integer factorization algorithm .

EDIT:

After digging, although CPAN (you should always), I found Math::Factor::XShere is an example (I also ridiculed a clean Perl example using grep / map):

#!/usr/bin/perl
use strict;
use warnings;
use 5.10.0;

use Math::Factor::XS qw/factors matches/;

my $num = 12;

say "Factors:";
my @factors = factors $num;
say for @factors;

say "Matches:";
say $_->[0] . "x" . $_->[1] for ( [ 1, $num ] , matches($num, \@factors));

# using grep 
say "Grep:";
my @grep_factors = map { [ $_ , $num / $_ ] } grep { !($num % $_) } (1 .. int sqrt $num);
say $_->[0] . "x" . $_->[1] for @grep_factors;
+6
source

Mark from 1 to sqrt(x)for dividers. Use them and their pairs. Watch out for the squares.

+5
source

All Articles