-
Notifications
You must be signed in to change notification settings - Fork 320
/
ch-2.pl
executable file
·65 lines (44 loc) · 1 KB
/
ch-2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/perl -s
use v5.16;
use Test2::V0;
use bigint;
our ($tests, $examples);
run_tests() if $tests || $examples; # does not return
die <<EOS unless @ARGV;
usage: $0 [-examples] [-tests] [N...]
-examples
run the examples from the challenge
-tests
run some tests
N...
list of numbers
EOS
### Input and Output
say total_power(@ARGV);
### Implementation
sub total_power {
my @s = sort {$a <=> $b} @_;
my $power;
while (defined (my $min = $s[0])) {
while (my ($offs, $max) = each @s) {
$power += $min * $max**2 * ($offs ? 2**($offs - 1) : 1);
}
} continue {
shift @s;
}
$power;
}
### Examples and tests
sub run_tests {
SKIP: {
skip "examples" unless $examples;
is total_power(2, 1, 4), 141, 'example 1';
}
SKIP: {
is total_power(2, 3, 5, 7), 1627, 'example from blog';
is total_power((2) x 64), (2**64 - 1) * 2 * 2**2,
'147573952589676412920';
}
done_testing;
exit;
}