Skip to content

Commit 66ad4a2

Browse files
committed
[euler] solution for problem 80
1 parent 0ef4319 commit 66ad4a2

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

categories/euler/prob080-andreoss.pl

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+

t/categories/euler.t

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,14 @@ subtest {
406406

407407
check-example-solutions($problem, $expected-output, @authors)
408408
}, "prob067";
409+
subtest {
410+
plan 1;
411+
my $problem = "prob080";
412+
my @authors = <andreoss>;
413+
my $expected-output = 40886;
409414

415+
check-example-solutions($problem, $expected-output, @authors)
416+
}, "prob080";
410417
subtest {
411418
plan 1;
412419

0 commit comments

Comments
 (0)