-
Notifications
You must be signed in to change notification settings - Fork 0
/
least_common_multiple.sh
executable file
·99 lines (85 loc) · 2.43 KB
/
least_common_multiple.sh
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
94
95
96
97
98
99
#!/bin/bash
######################################################################
# Find least common multiple of two integers
#
# The solution is based on formula LCM(a, b) = (a * b) / GCD(a, b)
######################################################################
set -o nounset
set -o errexit
######################################################################
# Validate arguments got with script invocation. Only two integers
# are allowed or one -h || --help string.
# Globals:
# none
# Arguments:
# $@ as all agrument passed with script
# Outputs:
# return 1 || 0 depend of check's result
######################################################################
check_input() {
valid_number_arg='^[1-9]{1}[0-9]{0,9}$'
valid_help_arg='(^-h$)|(^--help$)'
if [[ $# -eq 2 ]] && [[ $1 =~ $valid_number_arg ]] && [[ $2 =~ $valid_number_arg ]]; then
return 0
fi
if [[ $# -eq 1 ]] && [[ $1 =~ $valid_help_arg ]]; then
return 0
fi
return 1
}
print_help() {
printf "%s\n%s\n%s\n",\
"Find least common multiple of two integers"\
"Use $./least_common_multiple.sh 123 456 for normal use or enter arguments"\
"-h, --help to dispaly this help and exit."
}
print_error() {
echo "Valid input is two integer numbers greater than 0 or -h or --help for help"
}
######################################################################
# Get GCD of two integers using Euclidean algorithm
# Globals:
# none
# Arguments:
# $1, $2 as arguments passed with func incovation from get_lcm()
# Outputs:
# return GCD of two argument integers
######################################################################
get_gcd() {
local -i a="$1"
local -i b="$2"
while [[ $a -ne 0 ]] && [[ $b -ne 0 ]]; do
if [[ $a -gt b ]]; then
a=$(($a%$b))
else
b=$(($b%$a))
fi
done
echo $((a+b))
}
######################################################################
# Get LCM with formula LCM(a, b) = (a * b) / GCD(a, b)
# Globals:
# None
# Arguments:
# $1, $2 as agruments passed with script
# Outputs:
# return LCM of two argument integers
######################################################################
get_lcm() {
local -i gcd=1
local -i a="$1"
local -i b="$2"
gcd=$(get_gcd "$a" "$b")
echo $(($a*$b/$gcd))
}
main() {
local -i lcm
check_input "$@" || { print_error; exit 1; }
case "$1" in
-h | --help ) print_help; exit 0;;
* ) lcm=$(get_lcm "$1" "$2");;
esac
echo "$lcm"
}
main "$@"