From 94d1d4fbbcf0dd2d03b201fe5313dac31ff34ac1 Mon Sep 17 00:00:00 2001 From: Scimon Date: Thu, 7 Oct 2021 12:57:05 +0100 Subject: This weeks challenges --- challenge-133/simon-proctor/raku/ch-1.raku | 10 +++++++++ challenge-133/simon-proctor/raku/ch-2.raku | 33 ++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 challenge-133/simon-proctor/raku/ch-1.raku create mode 100644 challenge-133/simon-proctor/raku/ch-2.raku diff --git a/challenge-133/simon-proctor/raku/ch-1.raku b/challenge-133/simon-proctor/raku/ch-1.raku new file mode 100644 index 0000000000..c334ede333 --- /dev/null +++ b/challenge-133/simon-proctor/raku/ch-1.raku @@ -0,0 +1,10 @@ +#!/usr/bin/env raku + +#| For the integer N return the integer sqrt of it +sub MAIN ( Int \n ) { + say isqrt( n ); +} + +sub isqrt(UInt \n) { + (1..*).first( { $_ * $_ > n } ) - 1; +}; diff --git a/challenge-133/simon-proctor/raku/ch-2.raku b/challenge-133/simon-proctor/raku/ch-2.raku new file mode 100644 index 0000000000..38451aed62 --- /dev/null +++ b/challenge-133/simon-proctor/raku/ch-2.raku @@ -0,0 +1,33 @@ +#!/usr/bin/env raku + +use experimental :cached; + +#| Display the first n smith numbers +sub MAIN ( UInt \n = 10 ) { + .say for (2..*).grep( { is-smith-number($_) } )[^n]; +} + +multi sub is-smith-number( Int \n where n.is-prime --> False ) {} + +multi sub is-smith-number( Int \n --> Bool ) is pure { + my @factors = prime-factors( n ); + ([+] n.comb) == ([+] @factors.map( { [+] $_.comb } )); +} + +sub prime-factors( Int $n is copy --> Array ) is pure { + my @factors; + while ! $n.is-prime { + my \s = smallest-factor( $n ); + @factors.push(s); + $n = $n div s; + } + @factors.push($n); + return @factors; +} + +sub smallest-factor( Int \n --> Int ) is pure is cached { + for (2..(n div 2)).grep(*.is-prime) { + return $_ if n %% $_; + } + die "Something went wrong"; +} -- cgit