-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.js
More file actions
62 lines (50 loc) · 2.19 KB
/
program.js
File metadata and controls
62 lines (50 loc) · 2.19 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
// Function to determine the sign of an integer
function getSign(num) {
// Shift the sign bit of the integer to the rightmost position
let signBit = num >> 31;
// Use the sign bit to determine the sign:
// If the number is positive, signBit will be 0 (0000...0000).
// If the number is negative, signBit will be -1 (1111...1111).
// If the number is zero, the signBit will remain 0.
// We can then use the absolute value of signBit as the sign representation.
let sign = 1 - ((signBit + signBit) & 1);
return sign;
}
// Function to find the minimum of two integers using branchless approach
function minBranchless(a, b) {
// Calculate the difference between a and b
let diff = a - b;
// Calculate the sign bit of the difference
let signBit = diff >> 31;
// If a is less than b, the signBit will be -1 (1111...1111).
// If a is greater than or equal to b, the signBit 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.
let minValue = b + (diff & signBit);
return minValue;
}
// Function to check if a is smaller than b
function isSmaller(a, b) {
// Check if a is smaller than b
return (a - b) < 0;
}
// Function to find the minimum of two integers using a helper function
function minWithHelper(a, b) {
// If isSmaller(a, b) returns true, then a is smaller than b.
// In this case, we will return a + 0, effectively keeping a as the minimum.
// Otherwise, if isSmaller(a, b) returns false, then a is greater than or equal to b.
// In this case, we will return a + (b - a), which will be equal to b.
// This effectively returns the smaller of the two values.
return a + (b - a) * Number(isSmaller(a, b));
}
// Test the functions
let num1 = 42;
let num2 = -7;
let num3 = 0;
console.log(`Sign of ${num1}: ${getSign(num1)}`);
console.log(`Sign of ${num2}: ${getSign(num2)}`);
console.log(`Sign of ${num3}: ${getSign(num3)}`);
let a = 15;
let b = 9;
console.log(`Minimum of ${a} and ${b} (branchless): ${minBranchless(a, b)}`);
console.log(`Minimum of ${a} and ${b} (with helper): ${minWithHelper(a, b)}`);