How to resolve the algorithm Count in factors step by step in the Raku programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Count in factors step by step in the Raku programming language
Table of Contents
Problem Statement
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors. For the purpose of this task, 1 (unity) may be shown as itself.
2 is prime, so it would be shown as itself. 6 is not prime; it would be shown as
2 × 3
{\displaystyle 2\times 3}
. 2144 is not prime; it would be shown as
2 × 2 × 2 × 2 × 2 × 67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Count in factors step by step in the Raku programming language
Source code in the raku programming language
constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;
multi factors(1) { 1 }
multi factors(Int $remainder is copy) {
gather for @primes -> $factor {
# if remainder < factor², we're done
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($_).join(" × ") for 1..*;
sub factor($n is copy) {
$n == 1 ?? 1 !!
gather {
$n /= take 2 while $n %% 2;
$n /= take 3 while $n %% 3;
loop (my $p = 5; $p*$p <= $n; $p+=2) {
$n /= take $p while $n %% $p;
}
take $n unless $n == 1;
}
}
say "$_ == ", join " \x00d7 ", factor $_ for 1 .. 20;
use Prime::Factor;
say "$_ = {(.&prime-factors || 1).join: ' x ' }" for flat 1 .. 10, 10**20 .. 10**20 + 10;
You may also check:How to resolve the algorithm Prime decomposition step by step in the XPL0 programming language
You may also check:How to resolve the algorithm One of n lines in a file step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Higher-order functions step by step in the Euler Math Toolbox programming language
You may also check:How to resolve the algorithm Hello world/Newline omission step by step in the Groovy programming language
You may also check:How to resolve the algorithm Pell's equation step by step in the Go programming language