Advertisement
Guest User

Untitled

a guest
May 24th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. # Challenge #1
  2.  
  3. #`[ Slow, naive, brute force perfect number calculation
  4. sub is-perfect (Int $n) {
  5. ($n == sum grep $n %% *, 1 .. $n div 2) ??
  6. $n !!
  7. Empty
  8. }
  9. ]
  10.  
  11. # Faster perfect number calculation
  12. sub is-perfect (Int $n) {
  13. my $p = 2**$n - 1;
  14. $n.is-prime && $p.is-prime ??
  15. $p * 2**($n - 1) !!
  16. Empty
  17. }
  18.  
  19. # Returns in a reasonable time for up to ~15
  20. .say for ( 1..* ).map( *.&is-perfect ).head(15);
  21.  
  22.  
  23. # Challenge #2
  24.  
  25. # Pass in an optional width parameter to center the phrases within that width
  26. sub center (*@strings, :$width) {
  27. my $pad = ceiling $width ??
  28. $width / 2 !!
  29. 2 R/ chars max @strings, :by(*.chars);
  30. @strings.map( { ' ' x ($pad - .chars div 2) ~ $_ } ).join: "\n"
  31. }
  32.  
  33. say center("This", "is", "a test of the", "center function");
  34.  
  35. my ($, $columns) = qx/stty size/.words;
  36. say center("This", "is", "a test of the", "center function", :width($columns));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement