Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Challenge #1
- #`[ Slow, naive, brute force perfect number calculation
- sub is-perfect (Int $n) {
- ($n == sum grep $n %% *, 1 .. $n div 2) ??
- $n !!
- Empty
- }
- ]
- # Faster perfect number calculation
- sub is-perfect (Int $n) {
- my $p = 2**$n - 1;
- $n.is-prime && $p.is-prime ??
- $p * 2**($n - 1) !!
- Empty
- }
- # Returns in a reasonable time for up to ~15
- .say for ( 1..* ).map( *.&is-perfect ).head(15);
- # Challenge #2
- # Pass in an optional width parameter to center the phrases within that width
- sub center (*@strings, :$width) {
- my $pad = ceiling $width ??
- $width / 2 !!
- 2 R/ chars max @strings, :by(*.chars);
- @strings.map( { ' ' x ($pad - .chars div 2) ~ $_ } ).join: "\n"
- }
- say center("This", "is", "a test of the", "center function");
- my ($, $columns) = qx/stty size/.words;
- say center("This", "is", "a test of the", "center function", :width($columns));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement