-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.c
More file actions
67 lines (53 loc) · 2.25 KB
/
program.c
File metadata and controls
67 lines (53 loc) · 2.25 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
#include <stdio.h>
// Function to determine the sign of an integer
int getSign(int num) {
// Shift the sign bit of the integer to the rightmost position
int 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.
int sign = 1 - ((signBit + signBit) & 1);
return sign;
}
// Function to find the minimum of two integers using branchless approach
int minBranchless(int a, int b) {
// Calculate the difference between a and b
int diff = a - b;
// Calculate the sign bit of the difference
int 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.
int minValue = b + (diff & signBit);
return minValue;
}
// Function to check if a is smaller than b
int isSmaller(int a, int b) {
// Check if a is smaller than b
return (a - b) < 0;
}
// Function to find the minimum of two integers using a helper function
int minWithHelper(int a, int 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) * isSmaller(a, b);
}
int main() {
int num1 = 42;
int num2 = -7;
int num3 = 0;
printf("Sign of %d: %d\n", num1, getSign(num1));
printf("Sign of %d: %d\n", num2, getSign(num2));
printf("Sign of %d: %d\n", num3, getSign(num3));
int a = 15;
int b = 9;
printf("Minimum of %d and %d (branchless): %d\n", a, b, minBranchless(a, b));
printf("Minimum of %d and %d (with helper): %d\n", a, b, minWithHelper(a, b));
return 0;
}