-
Notifications
You must be signed in to change notification settings - Fork 0
/
Math.pm
executable file
·93 lines (68 loc) · 1.25 KB
/
Math.pm
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/perl
use strict;
use warnings;
package Math;
use Exporter "import";
our @EXPORT_OK = qw(average factorial gcd lcm);
use NumArrays qw(all_nums_are_equal min_index);
sub average {
my $num_items = scalar @_;
my $sum = 0;
foreach my $number (@_) {
$sum += $number;
}
return $sum / $num_items;
}
sub _euclid_gcd {
my $a = abs($_[0]);
my $b = abs($_[1]);
if($b > $a) {
# Switch a and b.
my $tmp = $a;
$a = $b;
$b = $tmp;
}
for(;;) {
my $r = $a % $b;
if($r == 0) {
return $b;
}
$a = $b;
$b = $r;
}
}
sub factorial {
my $number = abs($_[0]);
my $factorial = 1;
while($number > 0) {
$factorial *= $number;
$number--;
}
return $factorial;
}
sub gcd {
my $a = shift(@_);
while(scalar @_ > 0) {
my $b = shift(@_);
$a = _euclid_gcd($a, $b);
}
return $a;
}
sub lcm {
# Calculates the least common multiple of an array of numbers.
# https://en.wikipedia.org/wiki/Least_common_multiple#Using_a_simple_algorithm
if(scalar @_ < 1) {
return -1;
}
my @init_nums = ();
foreach my $num (@_) {
push(@init_nums, abs($num));
}
my @numbers = @init_nums;
until(all_nums_are_equal(@numbers)) {
my $min_index = min_index(@numbers);
$numbers[$min_index] += $init_nums[$min_index];
}
return $numbers[0];
}
1;