Skip to content

Commit 8590406

Browse files
committed
sys: util: Add gcd and lcm utilities
Add helpers to compute Greates Common Divisor (GCD) and Least Common Multiple (LCM). Signed-off-by: Phi Bang Nguyen <[email protected]> Signed-off-by: Trung Hieu Le <[email protected]>
1 parent 77a2946 commit 8590406

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

include/zephyr/sys/util.h

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1038,6 +1038,61 @@ static inline size_t sys_count_bits(const void *value, size_t len)
10381038
*/
10391039
#define SIGN(x) ((x > 0) - (x < 0))
10401040

1041+
/**
1042+
* @brief Compute the Greatest Common Divisor (GCD) of two integers
1043+
* using the Euclidean algorithm.
1044+
*
1045+
* @param a First integer
1046+
* @param b Second integer
1047+
*
1048+
* @return The greatest common divisor of a and b, always returns a positive value.
1049+
* If one of the parameters is 0, returns the absolute value of the other parameter.
1050+
*/
1051+
static inline int gcd(int a, int b)
1052+
{
1053+
int abs_a = (a < 0) ? -a : a;
1054+
int abs_b = (b < 0) ? -b : b;
1055+
1056+
if (abs_a == 0) {
1057+
return abs_b;
1058+
}
1059+
if (abs_b == 0) {
1060+
return abs_a;
1061+
}
1062+
1063+
int c = abs_a % abs_b;
1064+
1065+
while (c != 0) {
1066+
abs_a = abs_b;
1067+
abs_b = c;
1068+
c = abs_a % abs_b;
1069+
}
1070+
1071+
return abs_b;
1072+
}
1073+
1074+
/**
1075+
* @brief Compute the Least Common Multiple (LCM) of two integers.
1076+
*
1077+
* @param a First integer
1078+
* @param b Second integer
1079+
*
1080+
* @retval The least common multiple of a and b.
1081+
* @retval 0 if either input is 0.
1082+
*/
1083+
static inline int lcm(int a, int b)
1084+
{
1085+
if (a == 0 || b == 0) {
1086+
return 0;
1087+
}
1088+
1089+
int abs_a = (a < 0) ? -a : a;
1090+
int abs_b = (b < 0) ? -b : b;
1091+
int gcd_result = gcd(a, b);
1092+
1093+
return (abs_a / gcd_result) * abs_b;
1094+
}
1095+
10411096
#ifdef __cplusplus
10421097
}
10431098
#endif

0 commit comments

Comments
 (0)