|
| 1 | +use v6; |
| 2 | + |
| 3 | +=begin pod |
| 4 | +
|
| 5 | +=TITLE Square root digital expansion |
| 6 | +
|
| 7 | +=AUTHOR Your name (or nick, if you want) |
| 8 | +
|
| 9 | +L<https://projecteuler.net/problem=80> |
| 10 | +
|
| 11 | +It is well known that if the square root of a natural number is not an integer, then it is irrational. |
| 12 | +The decimal expansion of such square roots is infinite without any repeating pattern at all. |
| 13 | +The square root of two is 1.41421356237309504880..., and the digital sum of the first one |
| 14 | +hundred decimal digits is 475. |
| 15 | +
|
| 16 | +For the first one hundred natural numbers, find the total of the digital sums of the first |
| 17 | +one hundred decimal digits for all the irrational square roots. |
| 18 | +
|
| 19 | +The following algoritms was used for the solution: |
| 20 | +L<http://www.afjarvis.staff.shef.ac.uk/maths/jarvisspec02.pdf> |
| 21 | +
|
| 22 | +Expected result: 40886 |
| 23 | + |
| 24 | +=end pod |
| 25 | + |
| 26 | +use v6; |
| 27 | + |
| 28 | +my constant $limit = 100; |
| 29 | + |
| 30 | +sub sqrt-subtraction($n) { |
| 31 | + my Int $a = $n * 5 ; |
| 32 | + my Int $b = 5; |
| 33 | + while $b < 10 * 10 ** $limit { |
| 34 | + given $a <=> $b { |
| 35 | + when More | Same { |
| 36 | + # replace a with a − b, and add 10 to b. |
| 37 | + $a -= $b; |
| 38 | + $b += 10; |
| 39 | + } |
| 40 | + when Less { |
| 41 | + # add two zeros to a |
| 42 | + $a *= 100; |
| 43 | + # add a zero to b just before the final digit (which will always be ‘5’). |
| 44 | + $b = ($b - (my $x = $b % 10)) * 10 + $x; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + $b; |
| 49 | +} |
| 50 | + |
| 51 | +sub MAIN(Bool :$verbose = False) { |
| 52 | + say [+] do for 1 ... 100 -> $n { |
| 53 | + next if $n.sqrt.floor ** 2 == $n; |
| 54 | + my $x = [+] $n.&sqrt-subtraction.comb[^$limit]; |
| 55 | + say "$n $x" if $verbose; |
| 56 | + $x; |
| 57 | + } |
| 58 | + say "Done in {now - INIT now}" if $verbose; |
| 59 | +} |
| 60 | + |
| 61 | + |
| 62 | + |
0 commit comments