Prime decomposition

AUTHOR

TimToady

The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number.

Example: 12 = 2 Ɨ 2 Ɨ 3, so its prime decomposition is {2, 2, 3}

Task

Write a function which returns an array or collection which contains the prime decomposition of a given number, n, greater than 1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code).

More

http://rosettacode.org/wiki/Prime_decomposition#Raku

use v6;



my @primes = 2, 3, 5, -> $n is copy {
    repeat { $n += 2 } until $n %% none @primes ... { $_ * $_ >= $n }
    $n;
} ... *;

sub factors(Int $remainder is copy) {
    return 1 if $remainder <= 1;
    gather for @primes -> $factor {
        if $factor * $factor > $remainder {
            take $remainder if $remainder > 1;
            last;
        }

        # How many times can we divide by this prime?
        while $remainder %% $factor {
            take $factor;
            last if ($remainder div= $factor) === 1;
        }
    }
}

say "{factors 536870911}";

# vim: expandtab shiftwidth=4 ft=perl6

See Also

100-doors.pl

100 Doors

24-game.pl

24 game

accumulator-factory.pl

Accumulator factory

ackermann-function.pl

Ackermann function

arbitrary-precision-integers.pl

Arbitrary-precision integers (included)

balanced-brackets.pl

Balanced brackets

binomial-coefficient.pl

Binomial Coefficient

copy-a-string.pl

Copy a string

create-a-two-dimensional-array-at-runtime.pl

Create a two-dimensional array at runtime

hailstone-sequence.pl

Hailstone sequence

last-fridays-of-year.pl

Last fridays of the year

README.md

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.