-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.sh
More file actions
69 lines (52 loc) · 1.69 KB
/
program.sh
File metadata and controls
69 lines (52 loc) · 1.69 KB
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
#!/bin/bash
# Function to determine the sign of an integer
get_sign() {
local num=$1
# Shift the sign bit of the integer to the rightmost position
local sign_bit=$((num >> 31))
# Use the sign bit to determine the sign
local sign=$((1 - ((sign_bit + sign_bit) & 1)))
echo $sign
}
# Function to find the minimum of two integers using branchless approach
min_branchless() {
local a=$1
local b=$2
# Calculate the difference between a and b
local diff=$((a - b))
# Calculate the sign bit of the difference
local sign_bit=$((diff >> 31))
# If a is less than b, the sign_bit will be -1 (1111...1111).
# If a is greater than or equal to b, the sign_bit will be 0 (0000...0000).
# In the case where a is less than b, we will add the difference to b.
# Otherwise, we will add 0 to b, effectively keeping b as the minimum.
local min_value=$((b + (diff & sign_bit)))
echo $min_value
}
# Function to check if a is smaller than b
is_smaller() {
local a=$1
local b=$2
# Check if a is smaller than b
[ $((a - b)) -lt 0 ]
}
# Function to find the minimum of two integers using arithmetic
min_with_helper() {
local a=$1
local b=$2
# Returns 1 if a < b, 0 otherwise
local smaller=$(( (a - b) >> 31 & 1 ))
# a + (b - a) * smaller: if smaller=1, returns b; if smaller=0, returns a
echo $((a + (b - a) * smaller))
}
# Test the functions
num1=42
num2=-7
num3=0
echo "Sign of $num1: $(get_sign $num1)"
echo "Sign of $num2: $(get_sign $num2)"
echo "Sign of $num3: $(get_sign $num3)"
a=15
b=9
echo "Minimum of $a and $b (branchless): $(min_branchless $a $b)"
echo "Minimum of $a and $b (with helper): $(min_with_helper $a $b)"