*Find the prime factors of a given number.*

Prime factors are the prime numbers that divide the given integer number exactly.

In Task 28, *List of prime numbers*, weâ€™ve seen how to make a lazily evaluated list of prime numbers. This list is used in the program as a generator of the factor numbers for the tests.

my $n = 123456789;

my @list;

my @prime = grep {.is-prime}, 1..*;

my $pos = 0;

while $n > 1 {

Â Â Â Â my $factor = @prime[$pos];

Â Â Â Â $pos++;

Â Â Â Â next unless $n %% $factor;

Â Â Â Â $pos = 0;

Â Â Â Â $n /= $factor;

Â Â Â Â push @list, $factor;

}

say @list;Â# [3 3 3607 3803]

On each iteration, the number is tested with theÂ `$n %%Â $factor`

condition.Â If the factor has been found, it is added to theÂ `@list`

array, the current position in theÂ `@prime`

arrays is set back to 0 (because factors may repeat), and the numberÂ `$n`

is divided by theÂ `$factor`

value before the next iteration.Â The loop finishes when the value ofÂ `$n`

becomes equal to 1.