Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env perl6
- # Solution for Project Euler problem 159
- # https://projecteuler.net/problem=159
- use v6.c;
- sub MAIN(Int $limit = 10⁶, Bool :v(:$verbose) = False)
- {
- my $max = $limit - 1;
- # Start with the digital roots of 1..max
- # The digital root of n > 0 is just (n mod 9) || 9, so generate a list
- # of repeated 1..9s of exactly the right length
- my @mdsr = 0, |(|(1..9) xx ($max div 9)), |(1..($max % 9));
- say @mdsr if $verbose;
- # mdsr(n) = max(dr(n), mdsr(i) + mdsr(j)) for all i > j > 1 with n = i×j
- # so loop over all i and j and update mdsr(i×j) where necessary
- #for 2 .. ($max div 2) -> $i {
- loop (my $i = 2, my $max-i = $max div 2; $i <= $max-i; $i++) {
- #for 2 .. ($max div $i) -> $j {
- loop (my $j = 2, my $max-j = $max div $i; $j <= $max-j; $j++) {
- @mdsr[$i*$j] max= @mdsr[$i] + @mdsr[$j];
- }
- say "$i: ", @mdsr if $verbose;
- }
- # We need the sum from 2..limit, so subtract @mdsr[0]=0 and @mdsr[1]=1
- say “∑mdrs(n) for 1 < n < $limit is: ”, @mdsr.sum - 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement